[英]Calling method of child class from object of parent class in C++
我有一個Item
對象的動態列表,其初始化如下:
Item * items = new Item[size];
其中size
是先前初始化的整數。
我用Book
對象填充此列表,其中Book
是Item
的子級 。 Book
和Item
類都具有方法print
,該方法將某些信息數組輸出到控制台。 我希望能夠調用items[x].print()
以便在Book
調用print
方法,如下所示:
void print() {
Item::print(); //call to print method of parent class
<printing out some information>
}
基本上,我想調用Book
子類的print
方法,該子類又調用Item
的print
方法,該方法打印出更多常規信息。 但是,使用items[x].print()
僅在Item
調用print
方法。 如何在Item
類型的數組items
中調用Book
類的print
方法?
使用時
Item * items = new Item[size];
數組items
每個元素都是一個Item
對象。 即使print()
是一個虛函數,如果您使用以下方法,也不會調用Book::print()
:
items[x].print();
為了能夠調用Book::print()
,您需要存儲指針,而不是對象。
Item** items = new Item*[size];
然后,您可以使用:
items[x]->print();
只要您用正確定義的指針填充數組即可。
例:
Item** items = new Item*[5];
items[0] = new Book;
items[0]->print();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.