/*************************************************
**
** 代码描述: 通过类实例,熟悉构造函数、复制构造函数的声明与使用
** 创建人:慕灵阁-wupke
** 创建时间:2021-11-14
** 版本:3_3.cpp
**
*
***************************************************/#include<iostream>usingnamespace std;classPoint{//Point 类的定义public://外部接口Point(int xx =0,int yy =0){//构造函数
x = xx;
y = yy;}Point(const Point &p);//复制构造函数voidsetX(int xx){x=xx;}voidsetY(int yy){y=yy;}intgetX()const{return x;}intgetY()const{return y;}private://私有数据int x, y;};//成员函数的实现Point::Point(const Point &p){
x = p.x;
y = p.y;
cout <<"Calling the copy constructor"<< endl;}//形参为Point类对象的函数voidfun1(const Point& p){
cout << p.getX()<< endl;//p.setX(1);}//返回值为Point类对象的函数
Point fun2(){
Point a;return a;}//主函数intmain(){
Point a;//第一个对象A
Point b(a);//情况一,用A初始化B。第一次调用复制构造函数
cout << b.getX()<< endl;fun1(b);//情况二,对象B作为fun1的实参。第二次调用复制构造函数
b =fun2();//情况三,函数的返回值是类对象,函数返回时,调用复制构造函数
cout << b.getX()<< endl;system("pause");return0;}
示例4:
// 例4-4 /*** ****//*************************************************
**
** 代码描述: 通过类的组合,线段(Line)类,利用复制构造函数建立一个新对象,了解构造一个组合类过程中参数的变化、传递 经理的过程
(复制/构造/初始化的过程)
**
** 创建人:慕灵阁-wupke
** 创建时间:2021-11-14
** 版本:3_4.cpp
**
*
***************************************************/#include<iostream>#include<cmath>usingnamespace std;//定义point类classPoint{public:Point(int xx =0,int yy =0){
x = xx;
y = yy;}Point(Point &p);intgetX(){return x;}intgetY(){return y;}private:int x,y;};//复制构造函数实现Point::Point(Point &p){
x = p.x;
y = p.y;
cout <<"calling the copy constructor of Point"<< endl;}//类的组合classLine{//line 类的定义public://外部接口Line(Point xp1,Point xp2);Line(Line &l);doublegetLen(){return len;}private://设置私有成员
Point p1,p2;//point类的对象 p1,p2double len;};// 组合类的构造函数Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2){//初始化过程(要进入对应的复制/构造函数中进行复制传递)
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){//组合类的复制构造函数
cout <<"Calling the copy constructor of Line"<< endl;
len = l.len;}//主函数intmain(){
Point myp1(1,1),myp2(4,5);//建立Point类的对象
Line line(myp1, myp2);//建立Line类的对象
Line line2(line);//利用复制构造函数建立一个新对象(再走一遍复制/构造/初始化复制的过程)
cout <<"The length of the line is: ";
cout << line.getLen()<< endl;
cout <<"The length of the line2 is: ";
cout << line2.getLen()<< endl;system("pause");return0;}