自学内容网 自学内容网

C++:const成员

const修饰成员变量,要在初始化列表中进行初始化。

const修饰成员函数,要放在函数后,称为常函数。常函数不能修改普通成员变量。

const修饰的对象,称为常对象。常对象不能修改普通成员变量,只能读取。

常对象只能使用常函数。

#include<iostream>
using namespace std;

class AA
{
public:
const int a;
int b;
public:
AA() :a(100)
{
b = 200;
}
public:
void Show() const//AA const * const this
{
cout << a <<" "<< b << endl;
}
void SS()
{
cout << a << " " << b << endl;
}
};



int main()
{
AA aa;
aa.b = 20;
aa.Show();

const AA bb;
//bb.b = 20;不行
bb.Show();
//bb.SS();不行



return 0;
}


原文地址:https://blog.csdn.net/2301_80311224/article/details/142706500

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!