请帮忙修改一道C++代码:题目要求是构造一个类函数,main函数和输出结果都已经给出,只是希望把类补充上

完整代码如下:#include<iostream>#include<iomanip>#include<cmath>usingnamespacestd;classPoint... 完整代码如下:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
class Point
{
public:
double x,y;
Point(double x,double y)
{
this->x = x;
this->y = y;
cout<<"constructor begin!"<<endl;
}
~Point()
{
cout<<"destructor begin!"<<endl;
}
void show()
{
cout<<fixed<<setprecision(2)<<"Point("<<x<<","<<y<<")"<<endl;
}
double dist(Point p)
{
cout<<fixed<<setprecision(2);
return sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
}
};
int main()
{
Point p1(2.178, 2.0);
Point p2(3.0, 3.0);
Point p3(6.0, 7.0);
p1.show();
p2.show();
p3.show();
cout << p2.dist(p3) << endl; //两点距离
return 0;
}
题目要求输出如下:constructor begin!constructor begin!constructor begin!Point(2.18,2.00)Point(3.00,3.00)Point(6.00,7.00)5.00destructor begin!destructor begin!destructor begin!我这个代码会输出四个“destructor begin!”,不太懂析构,求修改!谢谢
展开
 我来答
kja910
推荐于2016-04-02 · TA获得超过6859个赞
知道小有建树答主
回答量:602
采纳率:100%
帮助的人:243万
展开全部
这个地方改成
double dist(Point &p)
{
cout<<fixed<<setprecision(2);
return sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
}

&是引用指的是本身,如果不用引用就会生成一个拷贝给局部域用,相当于创建了一个新的对象,局部域结束后就会释放,当然会多一次析构了。

局部传参尽量都用引用或指针,效率高也不容易出问题。
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
捐你妹8
2015-01-06 · TA获得超过638个赞
知道小有建树答主
回答量:351
采纳率:0%
帮助的人:383万
展开全部
将dist函数改下就可以了。

double dist(Point &p)
其他的不变。
问题的原因是,你使用普通传值会隐形的生成一个实例。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式