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

あつあつ備忘録

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

【C++】仮引数を受け取るコンストラクタ

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

  • コンストラクタ関数には引数を渡すことができる

study48.cpp

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class strtype {
    char *p;
    int len;
public:
    strtype( char * );
    ~strtype();
    void show();
};

strtype::strtype( char *ptr ) {
    len = strlen( ptr );
    p = ( char *) malloc( len + 1 );
    if ( !p ) {
        cout << "メモリ割り当てエラー" << endl;
        exit(1);
    }
    strcpy( p, ptr );
}

strtype::~strtype() {
    cout << "pを開放する" << endl;
    free( p );
}

void strtype::show() {
    cout << p << " - 長さ:" << len << endl;
}

int main() {
    strtype s1("This is a test."), s2("I like C++.");
    s1.show();
    s2.show();

    return 0;
}

コンパイル

$ g++ -o study48 study48.cpp 

実行

$ ./study48 
This is a test. - 長さ:15
I like C++. - 長さ:11
pを開放する
pを開放する

引用・参考はこちら

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