当前位置:   article > 正文

C++作业day3

C++作业day3

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

  1. #include <iostream>
  2. using namespace std;
  3. //定义一个 人 类
  4. class Per
  5. {
  6. private:
  7. string name; //姓名
  8. int age; //年龄
  9. float *height; //身高
  10. float *weight; //体重
  11. public:
  12. //有参构造函数
  13. Per(string name,int age,float height,float weight):name(name),age(age),height(new float(height)),weight(new float(weight))
  14. {
  15. cout << "Per::有参构造函数" << endl << endl;
  16. }
  17. //析构函数
  18. ~Per()
  19. {
  20. cout << "Per::析构函数" << endl << endl;
  21. delete height;
  22. delete weight;
  23. height = nullptr;
  24. weight = nullptr;
  25. }
  26. //拷贝构造函数
  27. Per(const Per &other):name(other.name),age(other.age),height(new float(*(other.height))),weight(new float(*(other.weight)))
  28. {
  29. cout << "Per::拷贝构造函数" << endl << endl;
  30. }
  31. };
  32. //定义一个 学生 类
  33. class Stu
  34. {
  35. private:
  36. float score; //成绩
  37. Per p1;
  38. public:
  39. //有参构造函数
  40. Stu(float score,string name,int age,float height,float weight):score(score),p1(name,age,height,weight)
  41. {
  42. cout << "Stu::有参构造函数" << endl << endl;
  43. }
  44. //析构函数
  45. ~Stu()
  46. {
  47. cout << "Stu::析构函数" << endl << endl;;
  48. }
  49. //拷贝构造函数
  50. Stu(const Stu &other):score(other.score),p1(other.p1)
  51. {
  52. cout << "Stu::拷贝构造函数" << endl << endl;
  53. }
  54. };
  55. int main()
  56. {
  57. Per person1("小明",15,165,100);
  58. Per person2(person1);
  59. Stu s1(135,"小红",15,168,102);
  60. Stu s2(s1);
  61. return 0;
  62. }

思维导图

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/252534
推荐阅读
相关标签
  

闽ICP备14008679号