实验三 构造函数与析构函数

本文通过三个实验详细探讨了C++中构造函数和析构函数的调用时机、顺序及对象初始化。实验涉及错误修复、拷贝构造函数的使用、动态内存管理和对象生命周期。实验旨在帮助读者深入理解类的定义、成员访问权限以及对象初始化的方法。
摘要由CSDN通过智能技术生成

实验目的和要求

  1、熟悉类的定义格式和类中成员的访问权限。

  2、构造函数与析构函数的调用时机与顺序。

  3、掌握对象的定义以及对象的初始化的时机与方法。

实验内容

  1、下面程序sy3_1.cpp中用ERROR标明的语句有错,在不删除和增加代码行的情况下,改正错误语句,使其正确运行。

  1. //sy3_1.cpp
  2. #include<iostream>
  3. using namespace std;
  4. class Aa
  5. {
  6. public:
  7. Aa( int i= 0){a=i; cout<< "Constructor"<<a<< endl;}
  8. ~Aa(){ cout<< "Destructor"<<a<< endl;}
  9. void print(){ cout<<a<< endl;}
  10. private:
  11. int a;
  12. };
  13. int main()
  14. {
  15. Aa a1(1),a2(2);
  16. a1.print();
  17. cout<<a2.a<< endl; //ERROR
  18. return 0;
  19. }

运行结果如下:


修改程序如下:

  1. //sy3_1.cpp
  2. #include<iostream>
  3. using namespace std;
  4. class Aa
  5. {
  6. public:
  7. Aa( int i= 0){a=i; cout<< "Constructor"<<a<< endl;}
  8. ~Aa(){ cout<< "Destructor"<<a<< endl;}
  9. void print(){ cout<<a<< endl;}
  10. private:
  11. int a;
  12. };
  13. int main()
  14. {
  15. Aa a1(1),a2(2);
  16. a1.print();
  17. a2.print();
  18. return 0;
  19. }

正确程序运行结果如下:



2、调试下列程序。

  1. //sy3_2.cpp
  2. #include<iostream>
  3. using namespace std;
  4. class TPoint
  5. {
  6. public:
  7. TPoint( int x, int y){X=x,Y=y;}
  8. TPoint(TPoint &p);
  9. ~TPoint(){ cout<< "Destructor is called\n";}
  10. int getx(){ return X;}
  11. int gety(){ return Y;}
  12. private:
  13. int X,Y;
  14. };
  15. TPoint::TPoint(TPoint &p)
  16. {
  17. X=p.X;
  18. Y=p.Y;
  19. cout<< "Copy-initialization Constructor is called\n";
  20. }
  21. int main()
  22. {
  23. TPoint p1(4,9);
  24. TPoint p2(p1);
  25. TPoint p3=p2;
  26. TPoint p4,p5( 2);
  27. cout<< "p3=("<<p3.getx()<< ","<<p3.gety()<< ")\n";
  28. return 0;
  29. }

在该程序中,将TPoint类的带有两个参数的构造函数进行修改,在函数体内增加下述语句:

cout<<"Constructor is called.\n";

(1)写出程序的输出结果,并解释输出结果。

修改程序如下:

  1. //sy3_2.cpp
  2. #include<iostream>
  3. using namespace std;
  4. class TPoint
  5. {
  6. public:
  7. TPoint( int x, int y){X=x,Y=y;}
  8. TPoint(TPoint &p);
  9. ~TPoint(){ cout<< "Destructor is called\n";}
  10. int getx(){ return X;}
  11. int gety(){ return Y;}
  12. private:
  13. int X,Y;
  14. };
  15. TPoint::TPoint(TPoint &p)
  16. {
  17. X=p.X;
  18. Y=p.Y;
  19. cout<< "Copy-initialization Constructor is called\n";
  20. cout<< "Constructor is called\n";
  21. }
  22. int main()
  23. {
  24. TPoint p1(4,9);
  25. TPoint p2(p1);
  26. TPoint p3=p2;
  27. cout<< "p3=("<<p3.getx()<< ","<<p3.gety()<< ")\n";
  28. return 0;
  29. }


原程序运行结果如下:

修改后的程序运行结果如下:


输出结果解释:


(2)按下列要求进行调试:

在主函数体内,添加下列说明语句:

TPoint  P4,P5(2);

  1. //sy3_2.cpp
  2. #include<iostream>
  3. using namespace std;
  4. class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值