如果我有一个基类的派生类,我想根据一个标志为它们中的任何一个指定一个对象,那么应该是什么定义指向所选对象的指针。C++继承:定义一个指向派生类或基类的指针
实施例:
void main(int argc, char* argv[])
{
class Base B;
class Derived D;
class Base *P; /* My question is output this definition */
int flag; /* This will be an input */
if(flag)
P = &B; /* Should refer to the base class B */
else
P = &D; /* Should refer to the derived class D
/* Then I'd use P in the rest of my code */
}
我的问题是如何将类指针P被定义为能够指代基于标志`标志” B(基类)或d派生类) ?
只要'Derived'派生自'Base',这就好了。什么不适合你? – jxh
谢谢jxh。我试图确定我的解决方案。我对定义部分感到困惑。可以将P定义为指向Base类的指针,然后为它指派一个指向派生类的指针吗?顺便说一句,其他方式也可以工作(即定义P如下:class Derived * P;)? –
由于'B'不是'Derived',因此您不能进行这项任务。 – jxh