
请帮忙修改一道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!”,不太懂析构,求修改!谢谢 展开
#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!”,不太懂析构,求修改!谢谢 展开
展开全部
这个地方改成
double dist(Point &p)
{
cout<<fixed<<setprecision(2);
return sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
}
&是引用指的是本身,如果不用引用就会生成一个拷贝给局部域用,相当于创建了一个新的对象,局部域结束后就会释放,当然会多一次析构了。
局部传参尽量都用引用或指针,效率高也不容易出问题。
double dist(Point &p)
{
cout<<fixed<<setprecision(2);
return sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
}
&是引用指的是本身,如果不用引用就会生成一个拷贝给局部域用,相当于创建了一个新的对象,局部域结束后就会释放,当然会多一次析构了。
局部传参尽量都用引用或指针,效率高也不容易出问题。
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询