测试普通类继承模板类出错解决方法
测试普通类继承模板类出错
#include <iostream>
using namespace std;
template <typename T>
class base
{
public:
virtual void hello(T t) = 0;
};
class child : public base <int>
{
public:
virtual void hello(T t)
{
cerr < < "hello world " < <endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
guang::child c;
c.hello(10);
return 0;
}
错误信息如下:
d:\myprograms\test_abstractclass\test_abstractclass\test_abstractclass.cpp(19) : error C2061: syntax error : identifier 'T '
d:\myprograms\test_abstractclass\test_abstractclass\test_abstractclass.cpp(27) : error C2259: 'child ' : cannot instantiate abstract class
due to following members:
'void base <T> ::hello(T) ' : is abstract
with
[
T=int
]
d:\myprograms\test_abstractclass\test_abstractclass\test_abstractclass.cpp(13) : see declaration of 'base <T> ::hello '
with
[
T=int
]
d:\myprograms\test_abstractclass\test_abstractclass\test_abstractclass.cpp(28) : error C2660: 'child::hello ' : function does not take 1 arguments
难道是普通类不能从模板类继承吗?
谢谢大家参与讨论
------解决方案--------------------
class child : public base <int>
{
public:
virtual void hello(int t)你继承的是base <int> ,没有T这个东西。
{
cerr < < "hello world " < <endl;
}
};
------解决方案--------------------
下面两种写法都可以
1.
template <typename T>
class child : public base <T>
{
public:
virtual void hello(T t)
{
cerr < < "hello world " < <endl;
}
};
这样用
child <int> c;
c.hello(10);
2.
class child : public base <int>
{
public:
virtual void hello(int t)
{
cerr < < "hello world " < <endl;
}
};
这样用
child c;
c.hello(10);
#include <iostream>
using namespace std;
template <typename T>
class base
{
public:
virtual void hello(T t) = 0;
};
class child : public base <int>
{
public:
virtual void hello(T t)
{
cerr < < "hello world " < <endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
guang::child c;
c.hello(10);
return 0;
}
错误信息如下:
d:\myprograms\test_abstractclass\test_abstractclass\test_abstractclass.cpp(19) : error C2061: syntax error : identifier 'T '
d:\myprograms\test_abstractclass\test_abstractclass\test_abstractclass.cpp(27) : error C2259: 'child ' : cannot instantiate abstract class
due to following members:
'void base <T> ::hello(T) ' : is abstract
with
[
T=int
]
d:\myprograms\test_abstractclass\test_abstractclass\test_abstractclass.cpp(13) : see declaration of 'base <T> ::hello '
with
[
T=int
]
d:\myprograms\test_abstractclass\test_abstractclass\test_abstractclass.cpp(28) : error C2660: 'child::hello ' : function does not take 1 arguments
难道是普通类不能从模板类继承吗?
谢谢大家参与讨论
------解决方案--------------------
class child : public base <int>
{
public:
virtual void hello(int t)你继承的是base <int> ,没有T这个东西。
{
cerr < < "hello world " < <endl;
}
};
------解决方案--------------------
下面两种写法都可以
1.
template <typename T>
class child : public base <T>
{
public:
virtual void hello(T t)
{
cerr < < "hello world " < <endl;
}
};
这样用
child <int> c;
c.hello(10);
2.
class child : public base <int>
{
public:
virtual void hello(int t)
{
cerr < < "hello world " < <endl;
}
};
这样用
child c;
c.hello(10);