我有一个继承自抽象基类的类。
class CStateBase
{
friend class CApplication;
friend class CGraphics;
virtual int Update() =0;
};
class CStateTitle: private CStateBase
{
friend class CApplication;
friend class CGraphics;
CApplication *f_App;
int m_iR;
int Update();
CStateTitle(CApplication *App);
~CStateTitle();
};
在另一个类的方法中,CStateTitle 被动态分配到一个CStateBase 指针中。但是,如果我使用该指针尝试访问变量 int m_iR,编译器会在 CStateBase 中查找该变量,因此会出错。如果我可以在基类中声明 virtual int m_iR,我认为它会工作得很好,但出于某种原因,它不允许我声明虚拟数据成员。解决此问题的推荐方法是什么?感谢您的帮助。
最佳答案
您应该从基类公开继承:
class CStateTitle: public CStateBase
否则 CStateTitle
从编译器的角度来看不是 CStateBase
,因此您不能多态访问 CStateTitle
对象通过 CStateBase
指针。
C++ 中不能有虚数据成员,只能有虚方法。因此,解决方法可能是为您的数据成员声明虚拟访问器方法。
关于c++ - 多态性 : Accessing inherited class variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3106038/