假設我有這樣的事情:如何避免C++爲特定類方法強制轉換?設計模式?
class Father {
public:
virtual int genericMethod (void) =0;
};
class Son1: public Father {
public:
int genericMethod()
{ }
};
class Son2: public Father {
public:
int genericMethod()
{ }
int specifClassMethod()
{ }
};
在主我做了以下內容:
Father * test = new Son2();
test->specifClassMethod(); //Can't do this! It is specific of Class Son2 and is not a virtual method in class Father!
這裏主要的問題是要知道更好的方式,通過父親的接口訪問Son2具體方法。我想知道是否有設計模式來解決這個問題或其他方式。我不想做演員陣容,也不想在演講中加入很多'if'。
問候,
愛德華
你的例子是有點做作,是否有可能使它更具體? – 2011-03-25 12:23:20
爲了比@Coda更加明確,您使用的實際設計是什麼,以便我們能夠指出它的缺陷?如果你的設計沒問題,那麼'dynamic_cast'是你的朋友。通常,使用'dynamic_cast'是嗅到代碼的標誌。 – 2011-03-25 12:27:04
不要忘記添加虛擬析構函數到基類。否則,刪除「Father * test = ...;刪除測試;」不會調用正確的析構函數。 – 2011-03-25 12:36:21