如果我有一个来自基类的派生类,并且我想基于一个标志指定一个指向其中任何一个对象的指针,那么指向所选对象的指针的定义应该是什么。
示例:
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 */
}
我的问题是如何根据标志`flag'来定义类指针P能够引用B(基类)还是D引用类?
答案 0 :(得分:3)
假设您的代码是基本形式:
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
)不会如上所述。