- 常量引用
int main()
{ // int &m = 10; // 错误, 引用必须引一块合法的内存空间(什么是合法的内存空间, 这个10在程序中有内存吗?)const int &m = 10; //加入const后,语法就通过了,编译器优化,类似 int temp=10; const int &m = temp; // 可以通过指针来修改 const值int *p = (int *)&m;*p = 1000;cout << m << endl;return 0;
}
- 常量引用的使用场景
// 引用常用作形参,这样不用进程值拷贝,const 加在引用前面是保证数据不被修改
void test1(const int &a) {
// a = 10000; //错误,不可以修改cout << a << endl;
}
void useConstRef() {int a = 3;test1(a);
}