访问在派生类中的类的受保护成员 [英] Access protected member of a class in a derived class

查看:169
本文介绍了访问在派生类中的类的受保护成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧的代码库在这里,他们使用受保护的成员变量。这是否一个好主意是否可以讨论。然而,代码必须编译精细与gcc3。
我有一个派生模板类Bar使用类模板中的protected成员x Foo像这样

i have an old codebase here, where they used protected member variables. Whether or not this is a good idea can be discussed. However, the code must have compiled fine with gcc3. I have a derived template class Bar that uses protected member x from class template Foo like so

template <class Something> class Foo {  
public:  
// stuff...  
protected:  
  some::type x;  
}

template <class Something> Bar : Foo<Something> {
public:
  void cleanup();
}

在cleanup()的方法声明中, / p>

And in the method declaration of cleanup() there is something done with x

template <class Something> void Bar<Something>::cleanup() {
  doSomeThingCleanUpLike (x);
}

这不适用于gcc4,虽然它应该使用gcc3。当我将它更改为

This does not work with gcc4, although it should have worked with gcc3. It works when I change it to

doSomeThingCleanUpLike (this->x);

为什么会这样?

推荐答案

在导出类中使用的表达式 x 根据标准中的规则,不依赖于派生类的任何模板参数。因此,查找在模板定义的上下文中发生,而不是在使用/实例化的时间点。即使模板的模板基类似乎是可见的,因为它是一个模板类,可能使用的特定实例化可能涉及专用模板,因此基类模板定义不能用于名称查找。

The expression x used in the derived class is, by the rules in the standard, not dependent on any template parameter of the derived class. Because of this, lookup happens in the context of the template definition and not at the point of use/instantiation. Even though the template base class of the template appears to be visible, because it is a template class the particular instantiation that might be used might involve specialized templates so the base class template definition cannot be used for name lookup.

通过将表达式更改为 this-> x ,使它成为一个依赖表达式( this 在类模板中总是取决于模板参数)。这意味着查找将发生在实例化上下文中,此时基类是完全已知的,其成员是可见的。

By changing the expression to this->x you are making it a dependent expression (this in a class template always depends on the template parameters). This means that lookup will occur in the instantiation context at which point the base class is fully known and its members are visible.

这篇关于访问在派生类中的类的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆