简体   繁体   English

访问派生类中的类的受保护成员

[英]Access protected member of a class in a derived class

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. 但是,代码必须与gcc3编译良好。 I have a derived template class Bar that uses protected member x from class template Foo like so 我有一个派生模板类Bar,它使用类模板Foo中的受保护成员x

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

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

And in the method declaration of cleanup() there is something done with x 在cleanup()的方法声明中,有一些用x完成的事情

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

This does not work with gcc4, although it should have worked with gcc3. 这不适用于gcc4,虽然它应该与gcc3一起使用。 It works when I change it to 当我将其更改为时,它可以工作

doSomeThingCleanUpLike (this->x);

Why is that the case? 为什么会这样?

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. 根据标准中的规则,派生类中使用的表达式x不依赖于派生类的任何模板参数。 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. 即使模板的模板基类看起来是可见的,因为它是模板类,可能使用的特定实例化可能涉及专用模板,因此基类模板定义不能用于名称查找。

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->x您将使其成为依赖表达式( this在类模板中始终取决于模板参数)。 This means that lookup will occur in the instantiation context at which point the base class is fully known and its members are visible. 这意味着将在实例化上下文中进行查找,此时基类是完全已知的并且其成员是可见的。

When you're defining the derived template, the compiler only knows the base template class' name but not its details, so compiler doesn't know the derived class has an inherited member. 当您定义派生模板时,编译器只知道基本模板类的名称而不知道其详细信息,因此编译器不知道派生类具有继承成员。 In order to tell the compiler of the member's existence, use this-> , just like you did. 为了告诉编译器成员的存在,请使用this-> ,就像你一样。

Actually, it is a duplicate of this question . 实际上,这是这个问题的重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM