Mir*_*cir -1 c++ inheritance templates constructor
我试图从基类(模板)继承,派生类也是模板,它们具有相同的类型 T。我收到编译错误:非法成员初始化:'Base' 不是基类或成员...
为什么?如何调用基类构造函数?
#include <iostream>
template<class T>
class Base {
public:
Base(T a) {
std::cout << "A: " << a << std::endl;
}
};
template<class T>
class Derived : public Base<T> {
public:
Derived(T a) :
Base(a) // this is the problem
{}
};
int main() {
int a = 1;
Derived<int> derived(a);
}
Run Code Online (Sandbox Code Playgroud)
由于Base是模板,因此需要在成员初始值设定项列表中指定模板参数:
Derived(T a) : Base<T>(a) {}
// ^^^
Run Code Online (Sandbox Code Playgroud)