#include<iostream>
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;
}
private: //需要定义私有成员,可以在public内赋值之后定义
int x,y;
};
Point::Point(Point &p){ //复制构造函数的实现
x=p.x;
y=p.y;
cout<<"Calling the copy constructor"<<endl;
}
void fun1(Point p){
cout<<p.getX()<<endl;
}
Point fun2(){
Point a(1,2);
return a;
}
int main(){
Point a(4,5);
Point b=a; //一:用a初始化b
cout<<b.getX()<<endl;
fun1(b); //二:对象b作为fun1的实参。
b=fun2(); //三:函数的返回值是类的对象
cout<<b.getX()<<endl; /*但fun2没有调用复制构造函数,编译器自动优化*/
return 0;
}
复制构造函数
最新推荐文章于 2023-07-11 11:45:36 发布