継承されたクラスのリストで管理

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
ホヅミ
記事: 110
登録日時: 14年前

継承されたクラスのリストで管理

#1

投稿記事 by ホヅミ » 11年前

現在私は継承されたクラスのリスト化を行いたいと思い以下のソースを書きました。
ですが結果は

>Interface1 Draw
>Interface2 Draw
>UserController Draw.
>UserController Draw.

となりリストでの実行ができません。

この辺に着手するのは初めてで、どうか書き方の指導をよろしくお願いいたします。


UserController.h

コード:

#ifndef _UserController_
#define _UserController_
#include <iostream>
using namespace std;
class UserController{
public:
	virtual void Draw(){
		cout << "UserController Draw." << endl;
	}

};
#endif _UserController_

Interface1.h

コード:

#ifndef _Interface1_
#define _Interface1_
#include "UserController.h"
class Interface1 : public UserController{
public:
	void Draw(){
		cout << "Interface1 Draw" << endl;
	}
};
#endif _Interface1_
Interface2.h

コード:

#ifndef _Interface2_
#define _Interface2_
#include "UserController.h"
class Interface2 : public UserController{
public:
	void Draw(){
		cout << "Interface2 Draw" << endl;
	}
};
#endif _Interface2_
main.cpp

コード:

#include "UserController.h"
#include "Interface1.h"
#include "Interface2.h"
#include <list>
int main(){
	
	UserController *uc1 = new Interface1();
	UserController *uc2 = new Interface2();

	list<UserController> uclist;
	uclist.push_back(*uc1);
	uclist.push_back(*uc2);
	uc1->Draw();
	uc2->Draw();
	list<UserController>::iterator it = uclist.begin(); // イテレータ
	while( it != uclist.end() )  // listの末尾まで
	{
		it->Draw();
		++it;  // イテレータを1つ進める
	}

	delete uc1;
	delete uc2;

	return 0;
}

ホヅミ
記事: 110
登録日時: 14年前

Re: 継承されたクラスのリストで管理

#2

投稿記事 by ホヅミ » 11年前

自己解決しました。
リストで管理する方もポインタにすればよかったのですね。
main.cpp

コード:

#include "UserController.h"
#include "Interface1.h"
#include "Interface2.h"
#include <list>
int main(){
	
	UserController *uc1 = new Interface1();
	UserController *uc2 = new Interface2();

	list<UserController*> uclist;
	uclist.push_back(uc1);
	uclist.push_back(uc2);
	
	list<UserController*>::iterator it = uclist.begin(); // イテレータ
	while( it != uclist.end() )  // listの末尾まで
	{
		(*it)->Draw();
		++it;  // イテレータを1つ進める
	}

	delete uc1;
	delete uc2;

	return 0;
}

閉鎖

“C言語何でも質問掲示板” へ戻る