C++ 类中的const关键字

时间:2024-08-31 12:07:08
//类中的const关键字
#include<iostream>
using namespace std; class Point{
public:
//这个const关键字本质上修饰的是this指针
int GetX() const //====>int GetX(const this)
{
//因为this被隐藏,所以const关键字只好写在函数后面
//x++;
//加上const关键字 报错 error C3490: 由于正在通过常量对象访问“x”,因此无法对其进行修改
//这个用法一般用在取私有成员属性的函数里,这样的函数一般不允许修改成员属性,
//所以可以加上const关键字增加安全性
return x;
}
private:
int x;
int y;
}; void main(){
system("pause");
}