cpp对非引用变量返回引用值

⌚Time: 2024-06-11 16:41:00

👨‍💻Author: Jack Ge

我测试了给非引用变量赋值函数的引用返回值。结果就很明显他不会跟随原变量的值改变。

#include <Iostream>

int b = 3;
int &get_value(){

    return b;
}
int main(){
    int &c = get_value();
    int a = get_value();
    std::cout<<"b:"<<b<<" a:"<<a<<" c:"<<c<<"\n";
    b = 4;//改变b的值
    std::cout<<"b:"<<b<<" a:"<<a<<" c:"<<c<<"\n";
    return 0;
}

结果

b:3 a:3 c:3
b:4 a:3 c:4

很明显只有指针和引用才能够跟随和修改原变量的值。类成员函数里面有引用变量就需要在初始化列表里面给变量赋值。如果是指针变量就随便在何处赋值了。