主题:C++类组合问题
小弟看教程中,有道题不明白,贴出来问一下,有点长.
#include <iostream.h>
#include <math.h>
class CPoint
{
public:
CPoint(int x=0, int y=0)
{
X=x;
Y=y;
cout << " CPoint 构造函数被调用" << endl;
};
CPoint(CPoint &p);
int GetX()
{
return X;
}
int GetY()
{
return Y;
}
private:
int X,Y;
};
CPoint::CPoint(CPoint &p)
{
X = p.X;
Y = p.Y;
cout << " CPoint 拷贝构造函数被调用" << endl;
cout << "(" << X << "," << Y << ")" << endl;
}
class CLine
{
public:
CLine(CPoint p1, CPoint p2);
float GetDistance();
private:
CPoint start;
CPoint end;
};
CLine::CLine(CPoint ps, CPoint pe): start(ps), end(pe)
{
cout << "CLine 构造函数被调用" << endl;
}
float CLine::GetDistance()
{
double x = double (end.GetX() - start.GetX() );
double y = double (end.GetY() - start.GetY() );
return (float) sqrt(x*x + y*y );
}
void main()
{
CPoint p1(1,1), p2(4,5);
CLine l(p1, p2);
cout << "The distance is :";
cout << l.GetDistance() << endl;
}
教程上说:
程序运行结果为:
CPoint 构造函数被调用
CPoint 构造函数被调用
CPoint 拷贝构造函数被调用
(4,5)
CPoint 拷贝构造函数被调用
(1,1)
CPoint 拷贝构造函数被调用
(1,1)
CPoint 拷贝构造函数被调用
(4,5)
CLine 构造函数被调用
The distance is :5
但我怎么看怎么觉得是:
程序运行结果为:
CPoint 构造函数被调用
CPoint 构造函数被调用
CPoint 拷贝构造函数被调用
(1,1)
CPoint 拷贝构造函数被调用
(4,5)
CPoint 拷贝构造函数被调用
(1,1)
CPoint 拷贝构造函数被调用
(4,5)
CLine 构造函数被调用
The distance is :5
CLine::CLine(CPoint ps, CPoint pe): start(ps), end(pe)这个函数不就是调用p1,p2,p1,p2吗?
我是初学者,很多地方不懂,书上又找不到,还望有人能帮忙.
#include <iostream.h>
#include <math.h>
class CPoint
{
public:
CPoint(int x=0, int y=0)
{
X=x;
Y=y;
cout << " CPoint 构造函数被调用" << endl;
};
CPoint(CPoint &p);
int GetX()
{
return X;
}
int GetY()
{
return Y;
}
private:
int X,Y;
};
CPoint::CPoint(CPoint &p)
{
X = p.X;
Y = p.Y;
cout << " CPoint 拷贝构造函数被调用" << endl;
cout << "(" << X << "," << Y << ")" << endl;
}
class CLine
{
public:
CLine(CPoint p1, CPoint p2);
float GetDistance();
private:
CPoint start;
CPoint end;
};
CLine::CLine(CPoint ps, CPoint pe): start(ps), end(pe)
{
cout << "CLine 构造函数被调用" << endl;
}
float CLine::GetDistance()
{
double x = double (end.GetX() - start.GetX() );
double y = double (end.GetY() - start.GetY() );
return (float) sqrt(x*x + y*y );
}
void main()
{
CPoint p1(1,1), p2(4,5);
CLine l(p1, p2);
cout << "The distance is :";
cout << l.GetDistance() << endl;
}
教程上说:
程序运行结果为:
CPoint 构造函数被调用
CPoint 构造函数被调用
CPoint 拷贝构造函数被调用
(4,5)
CPoint 拷贝构造函数被调用
(1,1)
CPoint 拷贝构造函数被调用
(1,1)
CPoint 拷贝构造函数被调用
(4,5)
CLine 构造函数被调用
The distance is :5
但我怎么看怎么觉得是:
程序运行结果为:
CPoint 构造函数被调用
CPoint 构造函数被调用
CPoint 拷贝构造函数被调用
(1,1)
CPoint 拷贝构造函数被调用
(4,5)
CPoint 拷贝构造函数被调用
(1,1)
CPoint 拷贝构造函数被调用
(4,5)
CLine 构造函数被调用
The distance is :5
CLine::CLine(CPoint ps, CPoint pe): start(ps), end(pe)这个函数不就是调用p1,p2,p1,p2吗?
我是初学者,很多地方不懂,书上又找不到,还望有人能帮忙.