⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 p2.cpp

📁 拷贝构造函数的实现,在类的组合中可以用其他类来定义数据的一些方法的实现源代码
💻 CPP
字号:
#include <iostream>
#include <math.h>
using namespace std;

class Point
{
public:
	Point(int xx,int yy){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 Distance                                //类的组合
{
public:
	Distance(Point xp1,Point xp2);
	double GetDis(){return dist;}
private:
	Point p1,p2;                             //在类的组合中可以用其他类来定义数据
	double dist;
};

Distance::Distance(Point xp1,Point xp2):p1(xp1),p2(xp2)
{
	cout<<"Distance 构造函数被调用"<<endl;
	double x=double(p1.GetX()-p2.GetX());
	double y=double(p1.GetY()-p2.GetY());
	dist=sqrt(x*x+y*y);
}
//main fuction
void main()
{
	Point myp1(1,1),myp2(4,5);
	Distance myd(myp1,myp2);
	cout<<"The distance is:";
	cout<<myd.GetDis()<<endl;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -