首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++模板类与继承

C++模板类与继承
EN

Stack Overflow用户
提问于 2011-02-07 08:38:46
回答 1查看 10.8K关注 0票数 9

可能重复:

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

下面的代码给我编译错误。怎么啦?

代码语言:javascript
复制
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

怎么解决这个问题?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-07 08:44:13

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

解决这个问题的方法是使用this->显式地在要访问的成员前缀

代码语言:javascript
复制
void foo() { 
    this->amount = this->amount * 2; // Or: this->amount *= 2;
}

这为编译器提供了一个明确的提示,说明名称amount来自何处,并且应该解决编译器错误。

如果有人想给出一个更详细的描述为什么会发生这个错误,我希望看到一个很好的解释。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4919322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档