【发布时间】:2014-02-20 05:00:41
【问题描述】:
如果我有一个基类的派生类,并且我想根据标志为它们中的任何一个对象分配一个指针,那么引用所选对象的指针的定义应该是什么。
例子:
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 定义为能够基于标志 `flag' 引用 B(基类)或 D 派生类)?
【问题讨论】:
-
只要
Derived派生自Base就可以了。什么不适合你? -
谢谢jxh。我试图确定我的解决方案。我对定义部分感到困惑。可以将 P 定义为指向基类的指针,然后将其分配给派生类的指针吗?顺便说一句,其他方式是否也可以工作(即定义 P 如下:class Derived *P;)?
-
不允许您进行该分配,因为
B不是Derived。 -
这个是可以的,但是指针只能用来调用B中声明的函数。如果你想调用D中不同的函数,那么你需要了解虚函数。
-
除非您的代码跨越二进制边界并且需要不同版本的代码之间的兼容性,否则无需担心太多。您可以使用基类指针类型来引用您的基类和派生类。或者改为参考。 :)
标签: c++ class pointers inheritance