LIFE LOG(ここにはあなたのブログ名)

あつあつ備忘録

ソフトやハード、時にはメカの備忘録をまとめていきます

【C++】コンストラクタ関数のオーバーロード

f:id:AtsuyaKoike:20190524095847p:plain:w300

コンストラクタ関数もオーバーロードできる

コンストラクタをオーバーロードするメリット

  1. 柔軟性を得る
  2. 配列のサポート
  3. コピーコンストラクタを作成すること

study145.cpp

#include <iostream>
using namespace std;

class myclass {
    int x;
public:
    myclass() {
        x = 0;
    }
    myclass( int n ) {
        x = n;
    }
    int getx() {
        return x;
    }
};

int main() {
    myclass o1(10);
    myclass o2;

    cout << "o1: " << o1.getx() << "\n";
    cout << "o2: " << o2.getx() << "\n";

    return 0;
}
$ ./study145 
o1: 10
o2: 0



stdudy149.cpp

#include <iostream>
using namespace std;

class myclass {
    int x;
public:
    myclass() {
        x = 0;
    }
    myclass( int n ) {
        x = n;
    }
    int getx() {
        return x;
    }
    void setx( int n ) {
        x = n;
    }
};

int main() {
    myclass *p;
    myclass ob(10);

    p = new myclass[10];
    if( !p ) {
        cout << "メモリ割り当てエラー\n";
        return 1;
    }
    
    for ( int i = 0; i < 10; ++i ) {
        p[i] = ob;
    }
    for ( int i = 0; i < 10; ++i ) {
        cout << "p[" << i << "]: " << p[i].getx();
        cout << "\n";
    }
    return 0;
}
$ ./study149 
p[0]: 10
p[1]: 10
p[2]: 10
p[3]: 10
p[4]: 10
p[5]: 10
p[6]: 10
p[7]: 10
p[8]: 10
p[9]: 10
  • 動的配列の初期化に使用することができる




引用・参考はこちら

f:id:AtsuyaKoike:20190524100759j:plain:w200
独習C++ 第4版 https://www.amazon.co.jp/dp/4798119768