//クラス宣言部
#include <iostream> // cout などを使うため
#include <cstring> // strlen 関数、strcpy 関数を使うため
#include <cstdlib> // malloc を使うため
using namespace std;
class strtype {
char *p;
int len;
public:
strtype(char *ptr); // コンストラクタ
~strtype(); // デストラクタ
void show();
};
|
//クラス実現部
// 文字列オブジェクトを初期化する (コンストラクタ)
strtype::strtype(char *ptr){ // (※1)
len = strlen(ptr); // (※3)
p = (char *) malloc(len+1); // (※4)
if(!p) // (※6)
{
cout << "メモリ割り当てエラー\n";
exit(1);
}
strcpy(p,ptr); // (※5)
}
// 文字列オブジェクトを破棄する際にメモリを解放する (デストラクタ)
strtype::~strtype()
{
cout << "pを解放する\n";
free(p);
}
void strtype::show()
{
cout << p << " - 長さ: " << len;
cout << "\n";
}
|
//クラス利用部
int main()
{
strtype s1("This is a test."), s2("I like C++."); // (※2)
// s1.show(); // 以下の三行は次のページ (第二回-05) で有効にすること
// s2.show();
// s2=s1;
s1.show();
s2.show();
return 0;
}
|


