如果我有一个来自基类的派生类,并且我想根据标志为它们中的任何一个的对象分配一个指针,那么指向所选对象的指针的定义应该是什么。
例子:
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(派生类)?
最佳答案
假设您的代码是基本形式:
class Base
{
public:
virtual ~Base() {}
};
class Derived : public Base
{};
然后 Derived
根据语言规则是 Base
,因此指向基类的指针可以包含 Derived
或一个 Base
。
Base* p = nullptr;
Base b;
Derived d;
if(flag == UseBase)
{
// Works
p = &b;
}
else if(flag == UseDerived)
{
// also works
p = &d;
}
就是说,Base
不是 Derived
,因此反向 (Derived* pd = &b
) 不会像上面写的那样工作.
关于C++ 继承 : defining a pointer to either derived or base class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21898541/