Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstring>
- #include <cstdlib>
- using namespace std;
- //構造体はコンストラクタとデストラクタも持てる
- //クラスとの違いは構造体のメンバはデフォルト公開
- struct strtype {
- strtype(char *ptr);
- ~strtype();
- void show();
- private:
- char *p;
- int len;
- };
- strtype::strtype(char *ptr)
- {
- len = strlen(ptr); //長さの取得
- p = (char *)malloc(len + 1); //メモリ領域の取得
- if (!p) {
- cout << "メモリ割り当てエラー" << endl;
- exit(1);
- }
- strcpy_s(p,len+1, ptr); //コピー
- }
- strtype::~strtype()
- {
- cout << "pの解放" << endl;
- free(p);
- }
- void strtype::show()
- {
- cout << p << "-- 長さ:" << len << endl;
- }
- int main()
- {
- strtype s1("Today is very hot.");
- strtype s2("Someone is calling you.");
- s1.show();
- s2.show();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement