C++模板类和继承

发布于 2024-10-15 23:30:13 字数 970 浏览 1 评论 0原文

可能的重复:
[常见问题解答] 为什么派生模板类无法访问基模板类的标识符? 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

走走停停 2024-10-22 23:30:13

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

解决此问题的方法是显式地为您要访问的成员添加 this-> 前缀:

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

这为编译器提供了关于名称 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->:

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文