有关C++类的问题
#include <iostream>
#include <cmath >
using namespace std;
class Point
{
public:
Point(double xx=0,double yy=0);
Point(Point &p);
double getX() {return x;}
double getY() {return y;}
private:
double x,y;
};
Point::Point(double xx,double yy)
{
x=xx;y=yy;
}
Point::Point(Point &p)
{
cout<<"调用Point类的拷贝构造函数"<<endl;
x=p.x;
y=p.y;
}
class Line
{
public:
Line(Point xp1,Point xp2);
Line(Line &l);
double getLength(){return len;}//len在Line类的构造函数中求出
private:
Point p1,p2;
double len;
};
Line::Line(Point xp1,Point xp2):p1(xp2),p2(xp2)
{
cout<<"调用Line类的构造函数"<<endl;
double x=static_cast<double>(p1.getX()-p2.getX());
double y=static_cast<double>(p1.getY()-p2.getY());
len=sqrt(x*x+y*y);
}
Line::Line(Line &l):p1(l.p1),p2(l.p2)
{
cout<<"调用Line类的拷贝构造函数"<<endl;
len=l.len;
}
int main()
{
Point mpy1(1,1),mpy2(4,5);
Line line(mpy1,mpy2);
Line line2(line);
cout<<"the length of line is:"<<line.getLength()<<endl;
cout<<"the length of line2 is:"<<line2.getLength()<<endl;
return 0;
}
这是求两点间距离的代码
这段代码为什么输出的距离总是0啊?
[解决办法]
Line::Line(Point xp1,Point xp2):p1(xp2),p2(xp2)
看看你这行,明显你让两个点一样了嘛~~~~~~~