以下多级类模板无法编译:
#include <iostream>
using namespace std;
template<typename T>
class A {
private:
A(void);
T _num_;
public:
A(T num): _num_(num){};
void printNum(void){
cout << _num_ << "\n";
}
};
template<typename T>
class B : public A<T> {
private:
B(void);
public:
B(T num): A(num){};
};
class C : public B<int> {
private:
C(void);
public:
C(int num): B(num){};
};
int main()
{
/* code */
auto c = C(2);
c.printNum();
return 0;
}
错误:成员初始值设定项'A'没有命名非静态数据成员或基类B(T num):A(num){};
错误:成员初始化器'B'没有命名非静态数据成员或基类 C(int num):B(num){};
但是删除模板完全没有问题。
#include <iostream>
using namespace std;
class A {
private:
A(void);
int _num_;
public:
A(int num): _num_(num){};
void printNum(void){
cout << _num_ << "\n";
}
};
class B : public A {
private:
B(void);
public:
B(int num): A(num){};
};
class C : public B {
private:
C(void);
public:
C(int num): B(num){};
};
int main()
{
/* code */
auto c = C(2);
c.printNum();
return 0;
}
答案 0 :(得分:0)
此问题是语法错误。除了类继承声明之外,类型名称T还必须传递给派生类ctor定义中的基本ctor调用。
class B : public A<T> {//...
B(T num): A<T>(num){}; //NOTE: <T> added to A ctor call.
和
class C : public B<int> {//...
C(int num): B<int>(num){}; //NOTE: <int> added to B ctor call.
完整的编译代码:
#include <iostream>
using namespace std;
template<typename T>
class A {
private:
A(void);
T _num_;
public:
A(T num): _num_(num){};
void printNum(void){
cout << _num_ << "\n";
}
};
template<typename T>
class B : public A<T> {
private:
B(void);
public:
B(T num): A<T>(num){};
};
class C : public B<int> {
private:
C(void);
public:
C(int num): B<int>(num){};
};
int main()
{
/* code */
auto c = C(2);
c.printNum();
return 0;
}