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を開放する
引用・参考はこちら
独習C++ 第4版
https://www.amazon.co.jp/dp/4798119768