C++模板类和继承
可能的重复:
[常见问题解答] 为什么派生模板类无法访问基模板类的标识符? c++ 中基类中受保护字段的问题< br> 无法访问类模板中的数据成员
以下代码给了我编译错误。怎么了?
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
如何解决这个问题?
谢谢
Possible Duplicates:
[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
Following code gives me compilation error. What is wrong?
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
How to fix this?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题与如何在从模板基类继承的模板类中查找名称有关。它背后的实际规则非常神秘,我不知道它们是什么;我通常必须查阅参考资料才能准确了解为什么这不起作用。
解决此问题的方法是显式地为您要访问的成员添加
this->
前缀:这为编译器提供了关于名称
amount
的来源的明确提示,以及应该可以解决编译器错误。如果有人想更详细地描述为什么会发生此错误,我很乐意看到一个很好的解释。
The problem here has to do with how names are looked up in template classes that inherit from template base classes. The actual rules behind it are pretty arcane and I don't know them off the top of my head; I usually have to consult a reference to learn precisely why this doesn't work.
The way to fix this is to explicitly prefix the member you're accessing with
this->
:This gives the compiler an unambiguous hint about where the name
amount
comes from and should resolve the compiler error.If someone wants to give a more detailed description of why this error occurs I'd love to see a good explanation.