可能重复:
FAQ Why doesn't a derived template class have access to a base template class' identifiers? Problem with protected fields in base class in c++
cannot access data member in a class template
下面的代码给我编译错误。怎么啦?
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怎么解决这个问题?
谢谢
发布于 2011-02-07 08:44:13
这里的问题与如何在从模板基类继承的模板类中查找名称有关。它背后的实际规则是相当神秘的,我不知道他们在我的头顶上;我通常需要查阅一个参考资料,以准确地了解为什么这不工作。
解决这个问题的方法是使用this->显式地在要访问的成员前缀
void foo() {
this->amount = this->amount * 2; // Or: this->amount *= 2;
}这为编译器提供了一个明确的提示,说明名称amount来自何处,并且应该解决编译器错误。
如果有人想给出一个更详细的描述为什么会发生这个错误,我希望看到一个很好的解释。
https://stackoverflow.com/questions/4919322
复制相似问题