// 组合类中复制函数的调用.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#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;
}
//~Point();
private:
int x,y;
};
Point::Point(Point &p)//实现复制构造函数
{
x=p.x;
y=p.y;
cout<<"Calling the copy constructor of Point"<<endl;
}
class Line
{
public:
Line(Point xp1,Point xp2);//构造函数
//~Line();
Line(Line &l);
double getLen()
{
return len;
}
private:
double len;
Point p1,p2;
};
Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2)//组和类实现构造函数格式//顺序p1,p2。。。。
{ //调用内嵌对象的构造函数(传递参数)
cout<<"Calling constructor of 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)//组合类实现复制构造函数格式//顺序p1,p2。。。。
{ //调用并为内嵌成员对象的复制构造函数传递参数
cout<<"Calling the copy constructor of Line"<<endl;
len=l.len;
}
//
//Line::~Line()
//{
//}
//
//Point::~Point()
//{
//}
int main()
{
Point myp1(1,1),myp2(4,5);//(11-14)
//复制构造函数的调用2:
// 函数的参数是类的对象,调用函数时进行形参和实参的结合时。
Line line(myp1,myp2);//{(27-32)2}--49--{(27-32)2}//顺序mpy2,myp1,。。。
Line line2(line);//用复制构造函数建立line2对象 56--{(27-32)2}--
cout<<"The length of the line is:";
cout<<line.getLen()<<endl;
cout<<"The length of the line2 is:";
cout<<line2.getLen()<<endl;
cin.get();
return 0;
}