C++常量引用
#include<iostream> using namespace std; void showValue(const int& val){ // val = 1000; //error: Cannot assign to variable 'val' with const-qualified type 'const int &' //不能把给常量引用类型的val变量赋值 cout << "val = " << val << endl; } /** * 测试常量引用 * 常量引用:使用const关键字修饰引用类型, 被修饰后将不能再使用该引用修改被引用的变量的值 * 常量引用的作用:常用于函数的形参, 防止误操作 */ int main() { //try define a reference type of constant //int& ref = 10; //error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int' const int& ref = 10; //when the complier encounters statement "const int& ref = 10;", //the complier will convert it to statement "int temp = 10;const int& ref = temp; int a = 10; int& ref2 = a; showValue(a); cout << "ref2 = " << ref2 << endl; system("pause"); return 0; }
常量引用常用于函数的形参, 防止误操作!
路漫漫其修远兮,吾将上下而求索。