我知道關鍵字virtual
使得基類的多態,如果我創建一個對象,並調用virtual function
,相應的功能將根據運行時間分配來調用,但我爲什麼要創建不同類型的對象。我的意思是使基類具有多態性?
Base *ptr = new Derived;
ptr->virtualfunction(); //calls the function which has implemented in Derived class.
如果我創建一個對象,以便
Derived *ptr = new Derived;
ptr->virtualfunction(); // which does the same without the need of making the function virtual.
這裏檢查例如:http://www.cplusplus.com/doc/tutorial/polymorphism/如果你需要這些對象的集合,或者你不知道對象的確切亞型(因爲它取決於配置,用戶輸入等),你需要多態。 –
所以你的問題是爲什麼需要虛擬方法呢? – Inspired
_「但我爲什麼要創建不同類型的對象」 _無論你的例子創建同一類型的對象,不同的是,你用它來指代它指針的類型,但是這兩個例子中創建一個'Derived'。 –