C++构造函数、拷贝构造函数 和 类组合构造函数调用的应用

例:已知坐标的两点,求距离。

#include<iostream.h>
#include<math.h>
class Point				 //点
{
	double x,y;
public:
	Point(double xx,double yy)        //构造函数
	{
		x=xx;
		y=yy;
	}
	Point(Point &p)               //拷贝构造函数,可不写,系统会自动创建。
	{
		x=p.x;
		y=p.y;
	}
	double GetX(){return x;}        //得到点x坐标
	double GetY(){return y;}	//得到y坐标
};
class Distance				//距离
{
	Point p1,p2;
	double dist;
public:
	Distance(Point a,Point b);
	double GetDis(){return dist;}
};
Distance::Distance(Point a,Point b):p1(a),p2(b)	
{  //构造函数求距离,其中a赋给p1,b赋给p2用了拷贝构造函数
	double x=double(p1.GetX()-p2.GetX());
	double y=double(p1.GetY()-p2.GetY());
	dist=sqrt(x*x+y*y);
}
void main()
{
	double a1,b1,a2,b2;
	cout<<"Please input the first point:\n";
	cin>>a1>>b1;
	Point myp1(a1,b1);			//第一个点
	cout<<"Please input the second point:\n";
	cin>>a2>>b2;
	Point myp2(a2,b2);			//第二个点
	cout<<"The distance is:\n";
	Distance myd(myp1,myp2);		//将myp1,myp2赋给形参a,b用了拷贝构造函数
	cout<<myd.GetDis()<<endl;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值