• c++day3


    1> 思维导图

    2>

    设计一个Per类,类中包含私有成员:姓名、年龄、指针成员身高、体重,再设计一个Stu类,类中包含私有成员:成绩、Per类对象p1,设计这两个类的构造函数、析构函数和拷贝构造函数。

    1. #include
    2. using namespace std;
    3. class Per{
    4. string name;
    5. int age;
    6. float *height;
    7. float *weight;
    8. public:
    9. Per()
    10. {
    11. cout << "Per的无参构造函数" << endl;
    12. }
    13. Per(string name,int age,float *height,float *weight)
    14. {
    15. this->name = name;
    16. this->age= age;
    17. this->height = height;
    18. this->weight = weight;
    19. cout << "Per的有参构造函数" << endl;
    20. }
    21. Per(Per &other)
    22. {
    23. this->name = other.name;
    24. this->age= other.age;
    25. height = new float;
    26. weight = new float;
    27. *height = *(other.height);
    28. *weight = *(other.weight);
    29. cout << "Per的深拷贝构造函数" << endl;
    30. }
    31. void set_h(float a)
    32. {
    33. *height = a;
    34. }
    35. void set_w(float b)
    36. {
    37. *weight = b;
    38. }
    39. ~Per()
    40. {
    41. cout << "准备释放堆区空间" << endl;
    42. delete height;
    43. delete weight;
    44. height = nullptr;
    45. weight = nullptr;
    46. cout << "Per的析构函数" << endl;
    47. }
    48. void show()
    49. {
    50. cout << "姓名:" << name << endl;
    51. cout << "年龄:" << age << endl;
    52. cout << "身高:" << *height << endl;
    53. cout << "体重:" << *weight << endl;
    54. }
    55. };
    56. class Stu{
    57. int score;
    58. public:
    59. Per p1;
    60. public:
    61. Stu(int score,string name,int age,float *height,float *weight):score(score),p1{name,age,height,weight}
    62. {
    63. cout << "Stu的有参构造函数" << endl;
    64. }
    65. Stu()
    66. {
    67. cout << "Stu的无参构造函数" << endl;
    68. }
    69. void show()
    70. {
    71. cout << "Stu中的成绩=" << score << endl;
    72. }
    73. };
    74. int main()
    75. {
    76. float *height = new float;
    77. *height = 188.2;
    78. float *weight = new float;
    79. *weight = 75.5;
    80. Stu s1(99,"亚索",25,height,weight);
    81. Stu s2=s1;
    82. cout << "s1中的个人信息" << endl;
    83. s1.show();
    84. s1.p1.show();
    85. cout << "s2中的个人信息" << endl;
    86. s2.show();
    87. s2.p1.show();
    88. cout << "s2修改后中的个人信息" << endl;
    89. s2.p1.set_h(180.5);
    90. s2.p1.set_w(80.5);
    91. s2.show();
    92. s2.p1.show();
    93. return 0;
    94. }

  • 相关阅读:
    使用dojo.declare进行组件化开发
    面试官:你能用异步模拟超时重传机制?
    【机器学习基础】正则化
    矩阵键盘独立接口设计(Keil+Proteus)
    攻防演练-紫队视角下的实战攻防演练组织
    leetcode 4405.统计子矩阵
    解决mybatis case when 报错的问题
    新手学PCB画板选什么软件
    redis:内存穿透、内存击穿、内存雪崩以及各数据类型应用场景
    浅析Java设计模式【3.4】——策略
  • 原文地址:https://blog.csdn.net/m0_72133977/article/details/133713303