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)
如何解决这个问题?
谢谢
这里的问题与如何在从模板基类继承的模板类中查找名称有关.它背后的实际规则是相当神秘的,我不知道它们在我的头顶; 我通常需要查阅参考资料,以准确了解为什么这不起作用.
解决此问题的方法是明确为您正在访问的成员添加前缀this->:
void foo() {
this->amount = this->amount * 2; // Or: this->amount *= 2;
}
Run Code Online (Sandbox Code Playgroud)
这为编译器提供了关于名称amount来源的明确提示,并应解决编译器错误.
如果有人想要更详细地描述为什么会出现这种错误,我很乐意看到一个很好的解释.
| 归档时间: |
|
| 查看次数: |
10380 次 |
| 最近记录: |