【问题标题】:C++ template class and inheritance [duplicate]C ++模板类和继承[重复]
【发布时间】:2011-02-07 08:38:46
【问题描述】:

可能的重复:
[常见问题] 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

如何解决这个问题?

谢谢

【问题讨论】:

  • 这个问题我已经看过好几次了,但是找不到链接。
  • 找到了一个,但如果有人能找到一个更好的问题,那就太好了:Problem with protected fields in base class in c++
  • @Chris:这是duplicate,这是lengthy explanation
  • 您是否注意到 D2 是从 D1 私下继承的?不是错误的原因,但可能是另一个错误。
  • @Gorpik- D2 实际上是从 D1 公开继承的,因为它是一个结构并且结构的默认继承模式是公共的。

标签: c++ templates inheritance


【解决方案1】:

这里的问题与如何在从模板基类继承的模板类中查找名称有关。它背后的实际规则非常神秘,我不知道它们是什么。我通常必须查阅参考资料才能准确了解为什么这不起作用。

解决此问题的方法是在您正在访问的成员前面显式添加 this-&gt;:

void foo() { 
    this->amount = this->amount * 2; // Or: this->amount *= 2;
}

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

如果有人想更详细地说明为什么会发生此错误,我很乐意看到一个很好的解释。

【讨论】:

  • 错误的原因是编译器不对模板基类成员做任何假设,以防基类的部分特化不包括其中一些成员。
  • 根据this:“关于 base 的一个有趣的事情是,直到类型 T 之后才创建它的任何成员函数。”所以编译器在定义时可能不知道任何成员,而不仅仅是函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多