2014-05-12 126 views
-4

我有一個類test_d公開繼承類test_b。類test_d具有函數getValues(),我需要使用類test_b的對象調用。我嘗試使用dynamic_castreinterpret_cast,但它沒有奏效。有沒有其他方法可以做到這一點?使用派生函數從基類

class test_b { 
// this is the base class 
}; 

class test_d : public test_b { 
// this is the derived class 

public int getValues() const; // this is the function I need to use. 
}; 

test_b* objB = new test_d; 
dynamic_cast<test_d*>(objB)->getValues(); // this is what I am doing. 
+1

這聽起來像一個嚴重有瑕疵的設計... –

+1

你可以詳細說明「它沒有工作」? 'dynamic_cast'看起來應該起作用(忽略基類不應該知道其派生類型的事實)。 – juanchopanza

+0

看起來像是一些破解的OOP – alex

回答

2

在你的界面,你應該聲明你的方法,純虛函數,然後在派生類中,你應該寫一個實現

class test_b 
{ 
public: 
    virtual int getValues() const = 0; 
}; 

class test_d : public test_b 
{ 
public: 
    virtual int getValues() const 
    { 
     return m_value; 
    } 
}; 

從你main()的地方:

test_b* objB = new test_d; 
objB->getValues(); 

這是OOP的基礎知識:界面和界面的實現

相關問題