xngzy 2021-11-02 17:06 采纳率: 100%
浏览 34
已结题

求帮我解释这两段c++输出结果


#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<<"Constructor is called\n";
cout <<"Copy-initialization Constructor is called\n";
}
int main(){
TPoint p1(4,9); 
TPoint p2(p1); 
TPoint p3=p2;
cout <<"p3 = ("<< p3. getx( )<<" ,"<< p3.gety( )<<")\n"; 
return 0;
}                                            


输出结果:


Constructor is called.
Copy-initialization Constructor is called
Copy-initialization Constructor is called
p3 = (4 ,9)
Destructor is called
Destructor is called
Destructor is called

```c++
#include
#include
using namespace std;
class My{
public:
My(double i=0){
x=y=i;
}
My(double i,double j){
x=i;y=j;
}
My(My &m){
x=m.x;
y=m.y;
}
friend double dist(My &a,My &b);
private:
double x,y;
};
double dist(My&a,My&b){
double dx=a.x-b.x;
double dy=a.y-b.y;
return sqrt(dxdx+dy dy);
}
int main(){
My ml,m2(15),m3(13,14);
My m4(m3);
cout<<"The distancel:"<<dist(ml,m3)<<endl;
cout<<"The distance2:"<<dist(m2,m3)<<endl;
cout<<"The distance3:"<<dist(m3,m4)<<endl;
cout<<"The distance4:"<<dist(ml,m2)<<endl;
return 0;
}

输出结果:

```The distancel:19.105
The distance2:2.23607
The distance3:0
The distance4:21.2132

  • 写回答

2条回答 默认 最新

  • 关注

    你的输出是错误的。正确的输出应该是:

    Constructor is called
    Copy-initialization Constructor is called
    Constructor is called
    Copy-initialization Constructor is called
    p3 = (4 ,9)
    Destructor is called
    Destructor is called
    Destructor is called
    

    1-2行是TPoint p2(p1)这句话调用拷贝构造函数时打印的。
    3-4行是TPoint p3=p2;这句话调用拷贝构造函数时打印的
    p3 = (4 ,9)这句话是cout <<"p3 = ("<< p3. getx( )<<" ,"<< p3.gety( )<<")\n"; 这句话打印的
    最后的Destructor is calle三句话是程序结束时,系统自动调用TPoint的析构函数时打印的,用来析构三个TPoint变量

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 11月10日
  • 已采纳回答 11月2日
  • 修改了问题 11月2日
  • 创建了问题 11月2日

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测