📄 demo_6_const_object_1.cpp
字号:
//***************************************************
#include <iostream.h>
class Sample
{
public:
Sample() {} //必须显式定义默认的拷贝构造函数
Sample(int i,int j) //构造函数
{
x=i;
y=j;
cout<<"Constructor Is Called."<<endl;
}
Sample(Sample &s) //拷贝构造函数
{
x=s.x;
y=s.y;
cout<<"Copy Constructor Is Called."<<endl;
}
void disp()
// void disp() const //const可区分函数重载
{
cout<<"x="<<x<<", y="<<y<<endl;
}
private:
int x,y;
};
void main()
{
//const对象在声明时必须同时初始化
Sample const A(1,2); //常对象声明并初始化
// const Sample A(1,2); //等价的
// Sample const A=Sample(1,2); //等价的
// const Sample A=Sample(1,2); //等价的
// A=Sample(3,4); //Error: 常对象不能作为左值被修改
// A.disp(); //Error: 只能用常成员函数访问常对象的数据成员
Sample const C; //const对象在声明时必须同时初始化
//必须显式定义默认的拷贝构造函数以在此调用,否则错误
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -