2014-02-20 127 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

相關問題