29 lines
745 B
C++
29 lines
745 B
C++
// 常量引用
|
||
// 相当于 常量指针常量
|
||
// 用法: const 数据类型 &变量名 = 其他变量或常量
|
||
|
||
// 注意:
|
||
// 一般的引用不能赋值常量(字面量),但是 const 引用可以赋值常量
|
||
#include <iostream>
|
||
|
||
using namespace std;
|
||
|
||
int main()
|
||
{
|
||
|
||
int x = 10;
|
||
const int &x1 = x;
|
||
|
||
// error: assignment of read - only reference ‘x1’
|
||
x1 -= 5; // const 修饰的引用不能修改内容
|
||
cout << "x = " << x << endl;
|
||
|
||
const int &x2 = 50;
|
||
cout << "x2 = " << x2 << endl;
|
||
|
||
// error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
|
||
int &x3 = 'a'; // 常量不能赋值给非常量引用
|
||
cout << "x3 = " << x3 << endl;
|
||
return 0;
|
||
}
|