【问题标题】:Access protected data members of the base class from the derived class从派生类访问基类的受保护数据成员
【发布时间】:2013-02-24 22:09:41
【问题描述】:

我有一个基类和派生类。我需要访问派生类中基类的受保护成员。但是,Eclipse 不允许我访问数据成员,就好像它是派生类的成员一样,而不关心它是否被继承。我该怎么做?

class BaseClass {
protected:
static int a;
int b;
}


class DerivedClass: public BaseClass {    
void SomeMethod {    
a=10; // cannot resolve symbol
b=10; // cannot resolve symbol
BaseClass::a=10; //does not complain
BaseClass::b=10; //does not complain    
}
}

【问题讨论】:

  • 作为一个好习惯,我可以建议使用'this-> b'
  • 这些是实际的编译器错误还是 Eclipse IDE 提供的语法/语义错误突出显示?
  • 当我使用 this-> 时,只有 DerivedClass 的数据成员会显示在自动完成中。我看不到基类的任何数据成员
  • @Bingo:这值得商榷。
  • @Bingo 谢谢,使用this-> 有效。它是使用模板与基类进行类继承。因此,我想这是需要here

标签: c++ inheritance derived-class data-members


【解决方案1】:

我无法完全理解您的问题,但修复语法错误,以下应该可以工作:

class BaseClass {
protected:
static int a;
int b;
}; // <-- Missing semicolon

int BaseClass::a = 0; // Define static member

class DerivedClass: public BaseClass {    
void SomeMethod() { // <-- Missing ()
a=10;
b=10; 
}
};// <-- Missing semicolon

【讨论】:

  • 是的,即使使用正确的语法,它也不起作用。你也在使用 Eclipse CDT 吗?
  • 不,目前没有。您对 Eclipse CDT 中的自动完成有疑问吗?
  • @user592748:“它不起作用”是什么意思?它编译吗?还是您的编辑只是在抱怨?
  • 实际上,我试图简化问题的代码。在这个过程中遗漏了一个关键的细节。它是使用模板继承类。使用this-&gt; 解决了该问题。这与两阶段查找有关,我从 question 中了解到
猜你喜欢
  • 2014-08-27
  • 2019-01-20
  • 2012-08-29
  • 2016-04-07
  • 1970-01-01
  • 2018-11-27
  • 2018-04-17
相关资源
最近更新 更多