ent*_*isi -4 c++ inheritance multi-level
假设存在3级继承.
A类<-B <-C.
B类的方法可以访问C派生的成员吗?
假设合适的继承模式.
小智 5
父类不能在没有"技巧"的情况下从子类访问数据,例如
class A
{
protected:
int m_a;
};
class B : public A
{
protected:
int m_b;
};
Run Code Online (Sandbox Code Playgroud)
B可以访问m_a,A不能访问m_b.要获得此行为,您可以使用多态和访问器函数
class A
{
protected:
virtual int GetVar() { return m_a; }
private:
int m_a;
}
class B : public A
{
protected:
virtual int GetVar() { return m_b; }
private:
int m_b;
}
Run Code Online (Sandbox Code Playgroud)
现在A可以通过调用GetVar()例如访问m_b
void A::DoSomething()
{
// I want to do something to the variable,
int myVar = GetVar();
}
Run Code Online (Sandbox Code Playgroud)
现在,如果键入实例A然后A::GetVar()被调用时,如果实例是类型B,然后B::GetVar()将改为调用