重生之我是懒羊羊980 2024-10-15 22:29 采纳率: 77.8%
浏览 0

根据运行结果分析组合类构造函数和析构函数调用顺序

#include<iostream>
#include<cmath>
using namespace std;
class Point    //Point类声明

{

public:

    Point(int xx=0, int yy=0) {

        X=xx;Y=yy;

        cout<<"Point构造函数被调用"<<endl;}

    Point(Point &p);

    ~Point(){

        cout<<"Point析构函数调用"<<endl;

    }

    int GetX() {return X;}

    int GetY() {return Y;}

private:

    int X,Y;

};



Point::Point(Point &p)    //拷贝构造函数的实现

{

    X=p.X;

    Y=p.Y;

    cout<<"Point拷贝构造函数被调用"<<endl;

}

//类的组合

class Line    //Line类的声明

{

public:    //外部接口

    Line (Point xp1, Point xp2,int c);

    Line (Line &);

    ~Line(){

     cout<<"Line析构函数调用"<<endl;

     }

    double GetLen(){return len;}

    int GetColor(){return color;}

private:    //私有数据成员

    Point p1,p2;    //Point类的对象p1,p2

    double len;    

    int color;

};

//组合类的构造函数

Line:: Line (Point xp1, Point xp2,int c)

:p1(xp1),p2(xp2)

{

    cout<<"Line构造函数被调用"<<endl;

    double x=double(p1.GetX()-p2.GetX());

    double y=double(p1.GetY()-p2.GetY());

    len=sqrt(x*x+y*y);

    color=c;

}

//组合类的拷贝构造函数

Line:: Line (Line &Seg): p1(Seg.p1),p2(Seg.p2)

{

    cout<<"Line拷贝构造函数被调用"<<endl;

    len=Seg.len;

    color=Seg.GetColor();

}

int  main()

{

    Point myp1(1,1),myp2(4,5);    //建立Point类的对象

    Line line(myp1,myp2,222);    //建立Line类的对象

    Line line2(line);//利用拷贝构造函数建立一个新对象

    cout<<"The length of the line is:";

    cout<<line.GetLen()<<endl;

    cout<<"The color of the line is:";

    cout<<line.GetColor()<<endl;

    cout<<"The length of the line2 is:";

    cout<<line2.GetLen()<<endl;

    cout<<"The color of the line2 is:";

    cout<<line2.GetColor()<<endl;

}

img


麻烦解读一下运行结果

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 创建了问题 10月15日

    悬赏问题

    • ¥30 模拟电路 logisim
    • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
    • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
    • ¥15 安装quartus II18.1时弹出此error,怎么解决?
    • ¥15 keil官网下载psn序列号在哪
    • ¥15 想用adb命令做一个通话软件,播放录音
    • ¥30 Pytorch深度学习服务器跑不通问题解决?
    • ¥15 部分客户订单定位有误的问题
    • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
    • ¥15 Bug traq 数据包 大概什么价