C++模板类和继承

ano*_*non 8 c++ inheritance templates

可能重复:
[FAQ] 为什么派生模板类不能访问基本模板类的标识符? c ++中基类中受保护字段的问题
无法访问类模板中的数据成员

以下代码给出了编译错误.怎么了?

struct Base {
   int amount;
};

template<class T> struct D1 : public Base {
};

template<class T>
struct D2 : D1<T> {
  void foo() { amount=amount*2; /* I am trying to access base class data member */ };
};

int main() {
  D2<int> data;
};


test.cpp: In member function 'void D2<T>::foo()':
test.cpp:11: error: 'amount' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?

谢谢

tem*_*def 9

这里的问题与如何在从模板基类继承的模板类中查找名称有关.它背后的实际规则是相当神秘的,我不知道它们在我的头顶; 我通常需要查阅参考资料,以准确了解为什么这不起作用.

解决此问题的方法是明确为您正在访问的成员添加前缀this->:

void foo() { 
    this->amount = this->amount * 2; // Or: this->amount *= 2;
}
Run Code Online (Sandbox Code Playgroud)

这为编译器提供了关于名称amount来源的明确提示,并应解决编译器错误.

如果有人想要更详细地描述为什么会出现这种错误,我很乐意看到一个很好的解释.

  • 错误的原因是编译器不对模板基类成员做任何假设,以防基类的部分特化不包括其中一些成员。 (2认同)

归档时间:

查看次数:

10380 次

最近记录:

15 年 前