Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. #include <cstdlib>
  4. using namespace std;
  5.  
  6. //構造体はコンストラクタとデストラクタも持てる
  7. //クラスとの違いは構造体のメンバはデフォルト公開
  8. struct strtype {
  9. strtype(char *ptr);
  10. ~strtype();
  11. void show();
  12. private:
  13. char *p;
  14. int len;
  15. };
  16.  
  17. strtype::strtype(char *ptr)
  18. {
  19. len = strlen(ptr); //長さの取得
  20. p = (char *)malloc(len + 1); //メモリ領域の取得
  21. if (!p) {
  22. cout << "メモリ割り当てエラー" << endl;
  23. exit(1);
  24. }
  25. strcpy_s(p,len+1, ptr); //コピー
  26. }
  27.  
  28. strtype::~strtype()
  29. {
  30. cout << "pの解放" << endl;
  31. free(p);
  32. }
  33.  
  34. void strtype::show()
  35. {
  36. cout << p << "-- 長さ:" << len << endl;
  37. }
  38.  
  39. int main()
  40. {
  41. strtype s1("Today is very hot.");
  42. strtype s2("Someone is calling you.");
  43.  
  44. s1.show();
  45. s2.show();
  46.  
  47. return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement