📄 demo_copy_constructor_a.cpp
字号:
//***************************************************
# include <iostream.h>
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: //私有数据
int X,Y;
};
//成员函数的实现
Point::Point(Point &p)
{
X=p.X;
Y=p.Y;
cout<<"Copy Constructor Is Called."<<endl;
}
//形参为Point类对象的函数
void fun1(Point p)
{
cout<<p.GetX()<<endl;
}
//返回值为Point类对象的函数
Point fun2()
{
Point A(1,2);
return A;
}
void main() //主程序
{
Point A(4,5); //定义对象A
// Point B(A); //情况1,用A初始化B。第1次调用拷贝构造函数
Point B=A; //等价的
cout<<B.GetX()<<endl;
fun1(B); //情况2,对象B作为fun1的实参。第2次调用拷贝构造函数
B=fun2(); //情况3,fun2的返回值赋对象B。第3次调用拷贝构造函数
cout<<B.GetX()<<endl;
}
/*
Copy Constructor Is Called.
4
Copy Constructor Is Called.
4
Copy Constructor Is Called.
1
Press any key to continue
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -