实验3 构造函数与析构函数(P279)

实验目的和要求

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

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

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

实验内容

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

//sy3_1.cpp
#include<iostream>
using namespace std;
class Aa
{
  public:
      Aa(int i=0){a=i;cout<<"Constructor"<<a<<endl;}
      ~Aa(){cout<<"Destructor"<<a<<endl;}
      void print(){cout<<a<<endl;}
  private:
    int a;
};
int main()
{
    Aa a1(1),a2(2);
    a1.print();
   cout<<a2.a<<endl;//ERROR
    return 0;
}

运行结果如下:


修改程序如下:

//sy3_1.cpp
#include<iostream>  
using namespace std;  
class Aa  
{  
  public:  
      Aa(int i=0){a=i;cout<<"Constructor"<<a<<endl;}  
      ~Aa(){cout<<"Destructor"<<a<<endl;}  
      void print(){cout<<a<<endl;}  
  private:  
    int a;  
};  
int main()  
{  
    Aa a1(1),a2(2);  
    a1.print();  
    a2.print();  
    return 0;  
}

正确程序运行结果如下:



2、调试下列程序。

//sy3_2.cpp
#include<iostream>
using namespace std;
class TPoint
{
public:
    TPoint(int x,int y){X=x,Y=y;}
    TPoint(TPoint &p);
    ~TPoint(){cout<<"Destructor is called\n";}
    int getx(){return X;}
    int gety(){return Y;}
private:
    int X,Y;
};
TPoint::TPoint(TPoint &p)
{
    X=p.X;
    Y=p.Y;
    cout<<"Copy-initialization Constructor is called\n";
}
int main()
{
    TPoint p1(4,9);
    TPoint p2(p1);
    TPoint p3=p2;
    TPoint p4,p5(2);
    cout<<"p3=("<<p3.getx()<<","<<p3.gety()<<")\n";
    return 0;
}

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

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

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

修改程序如下:

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值