5:virtual 仮想関数の効果
virtual SellProductとしていたおかげで、
基底クラスのメンバ関数から読んだ場合などでも、本来の型に応じて呼び分けられる。
仮想関数はどんな状況でも、そのオブジェクトの本来の型のものが呼ばれる。
main.cpp
#include "Product.h" #include "Fruit.h" #include "Vegetable.h" #includeusing namespace std; void Perchase(Product** List, int* QuantityList, int size) { for(int i = 0; i < size; i++) { List[i]->SellProduct(QuantityList[i]); } } int main() { Fruit* apple = new Fruit(300, 400, 20); Fruit* banana = new Fruit(200, 300, 30); Vegetable* tomato = new Vegetable(40, 60, 70); Vegetable* carrot = new Vegetable(50, 70, 45); //暗黙的にアップキャストをしている。警告はでない。 Product* List = {apple, banana, tomato, carrot}; const int SIZE = sizeof List / sizeof *List; //対照実験してみる。 tomato->IsThursday(true); banana->IsTuesday(true); int QuantityList = {1, 1, 5, 5}; //基底クラスではなく、本来のクラスの関数を呼び出せる。 Perchase(List, QuantityList, SIZE); for(int i = 0; i < SIZE; i++) { delete List[i]; } }
結果は、
trueに変更しました。 360になります。 //+apple 243になります。 //-banana サービスでもうひとつお付けします。 270になります。 //+tomato 315になります。 //-carrot 続行するには何かキーを押してください . . .
となり、うまくいっているということが分かる。