Jas*_*son 3 c++ inheritance constructor
在test.cpp文件中,我有这个:
template <typename T>
class A
{
public:
A(int a){};
virtual ~A();
private:
};
class B : public A<int>
{
public:
B(int a):A(a){};
virtual ~B();
private:
};
int main()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我编译它时,我得到这个:
jason@jason-linux:~/Documents/ECLibrary$ g++ -g -Wall -Wextra -pedantic-errors test.cpp -o tdriver
test.cpp: In constructor ‘B::B(int)’:
test.cpp:14: error: class ‘B’ does not have any field named ‘A’
test.cpp:14: error: no matching function for call to ‘A<int>::A()’
test.cpp:5: note: candidates are: A<T>::A(int) [with T = int]
test.cpp:3: note: A<int>::A(const A<int>&)
Run Code Online (Sandbox Code Playgroud)
我不想要我的基类的默认构造函数,因为它在我的代码中没有意义.我只是希望我的派生类执行基类的被调用构造函数,并为派生类中的额外内容做一些额外的构造.当我试图显式调用备用构造函数时,我真的不确定它为什么要尝试调用基类的默认构造函数.我在这里错过了什么吗?
谢谢
您可以将模板参数列表添加到A:
B(int a) : A<int>(a) { }
Run Code Online (Sandbox Code Playgroud)
请注意,您拥有的代码 - 在A没有模板参数列表的情况下使用- 是有效的C++.Comeau和Visual C++ 2010都按原样接受代码.
g ++ 4.3不接受没有模板参数列表的代码.也许有人可以测试更高版本的g ++或检查g ++ bug数据库以查看它是否是一个已知问题(我不经常使用g ++并且不熟悉他们的bug数据库).