リストを書き換えて生成オブジェクトを派生クラスポインタで振舞わせよ。
ただしクラス定義は変更しないものとするという問題なのですがどう書き換えればいいのでしょうか?
lang
1//リスト 2#include <iostream> 3#include <ctime> //システムタイマ用 4#include <cstdlib> //乱数発生用 5using namespace std; 6 7//会社クラス定義(基本クラス) 8class Company { 9public: 10 virtual void show(){} //仮想メソッド 11}; 12//////////////////////////////////////////////////////// 13//店舗クラス定義(派生クラス) 14class Shop : public Company { 15public: 16 void show(){ cout << "Shop" << endl; } 17}; 18//////////////////////////////////////////////////////// 19//金融業クラス定義(派生クラス) 20class Finance : public Company { 21public: 22 void show(){ cout << "Finance" << endl; } 23}; 24//////////////////////////////////////////////////////// 25int main() 26{ 27 Company* companyP = NULL; //基本クラスポインタ宣言 28 29 srand((unsigned)time(NULL)); //乱数の種設定 30 31 for(int i = 0, int j; i < 5; i++) 32 { 33 j = rand(); //乱数発生 34 35 if(companyP != NULL){ delete companyP; } //既生成済領域の解放 36 if(j % 2) companyP = new Shop; //店舗(派生)オブジェクトの生成 37 else companyP = new Finance; //金融業(派生)オブジェクトの生成 38 39 companyP->show(); 40 } 41 42 delete companyP; //最後に生成した領域の解放 43 return 0; 44} 45//---------------------------------------------------------------------------------------------- 46/問題 47#include <iostream> 48#include <ctime> //システムタイマ用 49#include <cstdlib> //乱数発生用 50using namespace std; 51 52//会社クラス定義(基本クラス) 53class Company { 54public: 55 virtual void show(){} //仮想メソッド 56}; 57//////////////////////////////////////////////////////// 58//店舗クラス定義(派生クラス) 59class Shop : public Company { 60public: 61 void show(){ cout << "Shop" << endl; } 62}; 63//////////////////////////////////////////////////////// 64//金融業クラス定義(派生クラス) 65class Finance : public Company { 66public: 67 void show(){ cout << "Finance" << endl; } 68}; 69//////////////////////////////////////////////////////// 70int main() 71{ 72 Shop* shopP = NULL; //派生クラスポインタ宣言 73 Finance* financeP = NULL; //派生クラスポインタ宣言 74 75 srand((unsigned)time(NULL)); //乱数の種設定 76 77 for(int i = 0; i < 5; i++) 78 { 79 //乱数を発生させてオブジェクト生成 80 if(rand() % 2) 81 82 83 84 85 } 86 87 88 return 0; 89} 90
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。