函数返回值的引用和给函数赋值
#include<iostream>
#include<string>
using namespace std;
int &test() {
int a = 10;
return a;
}
int& test01() {
int a = 10;
return a;
}
int main() {
int &ref = test();
cout << ref << endl;
cout << ref << endl;
test01() = 1000;
cout << ref << endl;
return 0;
}
运行结果
解析:函数的引用返回等于返回值本身,如
int &test() {
int a = 10;
return a;
}
int &ref = test();
等价于
int &ref = a;即 test() = a
因此可以对函数进行赋值操作,
似乎也可以认为,函数的引用返回,返回的是一个变量,而直接返回,返回的是一个常量,因此一个可以再次赋值,一个不可以。