2014-02-20 131 views
0

如果我有一个基类的派生类,我想根据一个标志为它们中的任何一个指定一个对象,那么应该是什么定义指向所选对象的指针。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派生类) ?

+1

只要'Derived'派生自'Base',这就好了。什么不适合你? – jxh

+0

谢谢jxh。我试图确定我的解决方案。我对定义部分感到困惑。可以将P定义为指向Base类的指针,然后为它指派一个指向派生类的指针吗?顺便说一句,其他方式也可以工作(即定义P如下:class Derived * P;)? –

+0

由于'B'不是'Derived',因此您不能进行这项任务。 – jxh

回答

3

假设你代码的基本形式为:

class Base 
{ 
public: 
    virtual ~Base() {} 
}; 

class Derived : public Base 
{}; 

然后,Derived是根据语言规则Base,因此指针的基类可以承装DerivedBase

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)不会工作。

+0

谢谢乍得。我必须在基类中使用虚拟吗? –

+0

如果您打算使用动态内存分配('new'),并且将通过基类指针释放内存('delete'),那么是的,为了保证适当的行为,'virtual'析构函数是必需的。 – Chad

+0

了解虚拟方法非常重要。你可能想让你的方法是虚拟的。 关于指针的事情,如果可能的话,引用甚至可能比指针更好。例如'Base&myClassRef =(flag == kUseBaseClass?b:d);' 在C++中,如果有一个有说服力的理由,你真的只想使用指针,就像NULL的值意味着什么。 – m24p

相关问题