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

来源:互联网 发布:如何练英语听力知乎 编辑:程序博客网 时间:2024/05/02 08:22

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

#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 0
原创粉丝点击