注册 登录
编程论坛 C++教室

新人求解

ljc424 发布于 2017-09-05 14:02, 1785 次点击
#include <iostream>
#include <cmath>

using namespace std;

class Point
{
public:
    Point(int xx=0, int yy=0){X=xx; Y=yy;}
    Point(Point &p);
    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
{
public:
    Line(Point xp1, Point xp2);
    Line(Line &);
    double GetLen(){return len;}
private:
    Point p1,p2;
    double len;
};


Line::Line(Point xp1, Point xp2):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);
}

Line::Line(Line &L):p1(L.p1),p2(L.p2)
{
    cout<<"Line2拷贝构造函数被调用"<<endl;
    len=L.len;
}

int main()
{
    Point myp1(1,1),myp2(4,5);
    Line line(myp1,myp2);
    Line line2(line);
    cout<<"The length of the line is:";
    cout<<line.GetLen()<<endl;
    cout<<"The length of the line2 is:";
    cout<<line2.GetLen()<<endl;

    return 0;
}
到网络上看到这段学习代码,不明白
Line::Line(Point xp1, Point xp2):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);
}
为什么不写成这样的
Line::Line(Point xp1, Point xp2)
{
    cout<<"Line构造函数被调用"<<endl;
    double x=double(xp1.GetX()-xp2.GetX());
    double y=double(xp1.GetY()-xp2.GetY());
    len=sqrt(x*x+y*y);
}
这两种有什么区别?分别用于什么情况下?
4 回复
#2
rjsp2017-09-05 15:41
这叫“成员初始化列表”,自己google吧
你这代码,唉,你连抄代码都不会,专挑垃圾的抄

我将你代码改了两次,更糊涂了,不知道你这代码的目的是什么。
如果是想……,不说了,自己找本正儿八经的书看看
#3
delphier_bc2017-09-06 21:33
同意楼上说的  这个是初始化类成员列表
至于代码....
#4
yangfrancis2017-09-07 12:05
Line::Line(Point xp1, Point xp2):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);
}
这是构造函数专用的对p1,p2两个成员变量进行赋值的方式。用你另外那个代码只是求线段的长度值,但没有建立那两个点。
#5
jinanman2017-09-22 17:01
这是构造函数专用的对p1,p2两个成员变量进行赋值的方式。用你另外那个代码只是求线段的长度值,但没有建立那两个点。
1