C++ | 重用Base类的受保护成员

arm*_*dle 1 c++ inheritance

假设我有一个Base&Derived类:

class Base{
 private:
  int* _privateIntPtrB;
 protected:
  int* _protectedIntPtrB;
 public:
  //methods which use
  //_privateIntPtrB and _protectedIntPtrB

class Derived: public Base{
 private:
  int* _privateIntPtrD;
 protected:
  int* _protectedIntPtrB; //I am redeclaring this var
 public:
  //methods which use
  //_privateIntPtrD and _protectedIntPtrB
Run Code Online (Sandbox Code Playgroud)

我的问题:在Derived类的方法中,Derived版本是否_protectedIntPtrB被使用?(我认为确实如此,但想确认).

如果一个方法没有被Derived类重新定义,那么_protectedIntPtrB 指针将使用哪个版本的Derived类?

我问的原因 - 我想_protectedIntPtrBDerived类中初始化不同,并希望_protectedIntPtrB在Derived类的所有实例中使用该版本.

Mik*_*our 5

在Derived类的方法中,是否使用了Derived版本_protectedIntPtrB

是的,它隐藏了基类成员,因此_protectedIntPtrB在范围内的不合格使用是DerivedDerived::_protectedIntPtrB.(如果符合条件,基类变量仍然可用Base::_protectedIntPtrB).

如果Derived类没有重新定义方法_protectedIntPtrB,那么指向Derived类的指针将使用哪个版本?

基类变量.派生类的数据成员不能从基类中获得.

我问的原因 - 我想_protectedIntPtrB在Derived类中进行不同的初始化,并希望在Derived类的_protectedIntPtrB所有实例中使用该版本.

通常,使派生类的行为与其基类行为不同的最佳方法是覆盖虚函数.如果你想要确切地想要实现什么,那可能会更好:找出你想要修改的行为,并将其封装在虚函数中.