にたまごほうれん草アーカイブ

はてなダイアリーで書いてた「にたまごほうれん草」という日記のアーカイブです。現在は「にたまごほうれん草ブログ」を運営中です。

初めてのC++

Cでオブジェクト指向的記述をしようとしているのに、C++のコードを今まで書いたことがない私。
せっかくなので、CでOOPの参考という意味も込めて、テストコードを書いてみることにした。
とりあえずぐぐって出てきた入門サイトに書いてある内容を分かった範囲で一つのコードにまとめてみた。

#include <iostream>
using namespace std; /* <- とりあえずはこれが必要なんだって */

class TestClass { /* クラスの宣言 */
protected:
    int x;              /* privateなメンバ変数 */
public:
    TestClass(int val); /* コンストラクタ */
    ~TestClass();       /* デストラクタ   */
    void printx();
};

TestClass::TestClass(int val) { /* コンストラクタの定義 */
    x = val;
}

TestClass::~TestClass() { /* デストラクタの定義 */
    x = 0;
    cout << x << endl;
}

void TestClass::printx() { /* メンバ関数の定義 */
    cout << x << endl;
}

class TestClassExt : public TestClass { /* TestClassを継承したTestClassExt */
protected:
    int y; /* 子クラスのメンバ変数 / xは親クラスで定義 */
public:
    TestClassExt(int valx, int valy);
    ~TestClassExt();
    void printy();
};

TestClassExt::TestClassExt(int valx, int valy) : TestClass(valx) {
    /* super(valx)的なものは↑に付けるのね */
    y = valy;
}

TestClassExt::~TestClassExt() { /* 子クラスのデストラクタ */
    cout << x + y << endl;
}

void TestClassExt::printy() {
    cout << y << endl;
}

int main(int argc, char *argv[])
{
    TestClass *tc;
    TestClassExt *tce;

    tc = new TestClass(10);
    tc->printx();
    // cout << tc->x << endl; /* <- コンパイルエラーが出る */
    delete tc;

    tce = new TestClassExt(100, 200);
    tce->printx(); /* 親クラスTestClassのメンバ関数 */
    tce->printy(); /* 子クラスTestClassExtで定義したメンバ関数 */
    delete tce;

    return 0;
}

出力

$ ./cpptest
10        // <- tc->printx()の結果
0         // <- TestClassのデストラクタの出力
100       // <- tce->printx()の結果
200       // <- tce->printy()の結果
300       // <- TestClassExtのデストラクタの出力
0         // <- TestClassのデストラクタの出力
                (子のあとに親のデストラクタを実行)

C++でまだ知らないものキーワード

virtual, friend, template, STL, 参照型