参考:https://www.cnblogs.com/xudong-bupt/p/3509567.html
C++中的const
C++ const 允许指定一个语义约束,编译器会强制实施这个约束,允许程序员告诉编译器某值是保持不变的。如果在编程中确实有某个值保持不变,就应该明确使用const,这样可以获得编译器的帮助。
const 修饰变量
#include<iostream>
using namespace std;
int main(){
int a;
const int b=1;
//b=1;//错误
//const位于*左侧,表示指针所指数据是常量,不能通过解引用修改该数据;指针本身是变量,可以指向其他的内存单元
const int*ptr=&a;
ptr=&b;//正确
//*ptr=3;//错误
cout<<*ptr<<endl;
//const位于*右侧,表示指针本身是常量,不能指向其他内存地址;指针所指的数据可以通过解引用修改
int *const ptr2=&a;
*ptr2=2;//正确
//ptr2=&a;//错误
cout<<*ptr2<<endl;
//两个const,*左右各一个,表示指针和指针所指数据都不能修改
const int*const ptr3=&a;
//ptr3=&a;//错误
//*ptr3=3;//错误
return 0;
}
const 修饰成员函数
- const修饰的成员函数不能修改任何的成员变量
- const成员函数不能调用非onst成员函数,因为非const成员函数可以会修改成员变量
class tt{
public:
int a;
public:
void change(){
a=1;
}
int test()const{
a=12;//错误,const修饰的成员函数不能修改任何的成员变量
change();//错误, const成员函数不能调用非onst成员函数
}
};