【C++】コンストラクタ関数とデストラクタ関数
study41.cpp
#include <iostream> #include <cstring> #include <cstdlib> using namespace std; #define SIZE 255 class strtype { char *p; int len; public: strtype(); ~strtype(); void set( char * ); void show(); }; strtype::strtype() { p = ( char * ) malloc(SIZE); if ( !p ) { cout << "メモリ割り当てエラー" << endl; exit(1); } *p = '\0'; len = 0; } strtype::~strtype() { cout << "pを開放する" << endl; free(p); } void strtype::set( char *ptr ) { if ( strlen( ptr ) >= SIZE ) { cout << "文字列が大きすぎる" << endl; return; } strcpy( p, ptr ); len = strlen( p ); } void strtype::show() { cout << p << " - 長さ:" << len << endl; } int main() { strtype s1, s2; s1.set( "This is a test." ); s2.set( "I like C++." ); s1.show(); s2.show(); return 0; }
コンパイル
$ g++ -o study41 study41.cpp
Warningがでますが、今回は気にしないということで。
実行
$ ./study41 This is a test. - 長さ:15 I like C++. - 長さ:11 pを開放する pを開放する