C ++多级类模板构造函数无法编译

时间:2019-02-24 17:30:02

标签: c++ class templates constructor multi-level

以下多级类模板无法编译:

#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;
}

1 个答案:

答案 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;
}