//#define _CRT_SECURE_NO_WARNINGS #include using namespace std; #include "list2.h" // 8-3 ///////////////////////////////////////////////////// // 整数を格納する Integerクラスを作成 // Elemから派生して、Printという仮想関数を実装 class Integer : public Elem { //private: protected: // 8-2 int i_x; public: Integer(int i) { i_x = i; } void Print() { cout << i_x << endl; } }; ///////////////////////////////////////////////////// // 文字列を格納する String クラスを作成 class String : public Elem { private: char* buf; public: String(const char*); ~String(); void Print() { cout << "\"" << buf << "\"" << endl; } }; // コンストラクタ // 文字列の領域を割り当ててコピー String::String(const char* str) { buf = new char[strlen(str)+ 1]; strcpy_s(buf, strlen(str)+ 1, str); } // デストラクタ // 文字列を格納した領域を解放 String::~String() { cout << "Stringのデストラクタ" << buf << endl; // 8-1 delete buf; } ///////////////////////////////////////////////////// // Coordクラスを作成 (8-2) // Integerから派生して、Printという仮想関数を実装 class Coord : public Integer { protected: int i_y; public: Coord(int x, int y): Integer(x) { i_y = y; } void Print() { cout << "(" << i_x << "," << i_y << ")" << endl; } }; //////////////////////////////////////////////////////// void main() { /* 8-3 メモリリークのチェックのための関数 */ /* プログラム終了時に自動的に _CrtDumpMemoryLeaks()が呼び出される */ /* 中級編 レポート課題:文字列クラスの作成 を参照 */ _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); //Listクラスのインスタンスを作成 List list(100); // Elemの派生クラスであればどんどん追加 list.Add(new Integer(100)); list.Add(new Integer(200)); list.Add(new Integer(300)); list.Add(new String("hello")); list.Add(new String("C++")); list.Add(new String("world!")); list.Add(new Coord(3, 4)); // 8-2 // 印刷 list.Print(); cout << "-------" << endl; //要素の並びの反転 list.Reverse(); //再び印刷 list.Print(); // 8-3 //List2クラスのインスタンスを作成 List2 list2(10); list2.Add(new Integer(1)); list2.Add(new Integer(2)); list2.Add(new Integer(3)); list2.Print(); cout << "---" << endl; list2.Delete(1); // 1番目の要素を削除 list2.Print(); }