Const关键字作用
在c语言中,const修饰的是只读变量,并不是一个常量,本质还是一个变量。
const修饰的变量会占用内存空间,本质上const只对编译器有用,它告诉编译器,这个变量是只读的。
Effective C++ 条款02/条款03:
const允许你指定一个语义约束,而编译器会强制实施这项约束。
1. const修饰全局变量/局部变量
2. const修饰指针
3. const修饰函数参数
4. const修饰函数返回值
5. const修饰成员函数
编译器如何处理Const
读一般的变量的时候,首先获取该变量的地址,然后到该地址去取数据。const变量是如何被读取?
#include <iostream>
using namespace std;
const int b = 2;
int main() {
const int a = 1;
const int * pa = &a; //指针pa指向常量a所在的内存
int * p_var = const_cast<int *>(pa); //强制转换const指针为非const
*p_var = 11;
int *pc = (int *)(&a);
*pc = 13;
int *pb = (int *)(&b);
//*pb = 12; error
cout << "a= " << a << endl;
cout << "Address a = " << (&a) << endl;
cout << "pa = " << *pa << endl;
cout << "Address pa = " << (pa) << endl;
cout << "pb = " << *pb << endl;
cout << "Address pb = " << (pb) << endl;
cout << "pc = " << *pc << endl;
cout << "Address pc = " << (pc) << endl;
cout << "p_var = " << *p_var << endl;
cout << "Address p_var = " << (p_var) << endl;
return 0;
}
运行结果:
a= 1
Address a