表达式作为左值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhao3132453/article/details/82889571

示例代码:

#include <iostream>
 
using namespace std;
 
 int getNum1()
{
    static int a = 10;
    return a;
}
 
int& getNum2()
{
    static int a = 10;
    cout<<a<<endl;
    return a;
}
    
int main()
{
    //getNum1() = 20; //error
    
    getNum2() = 30;
 
    getNum2(); //a =30
    
    return 0;
}

总结:

1、第一个函数返回的是一个数,所以不能作为左值

2、第二个函数返回的是一个变量(a的引用),所以可以作为左值

3、修改函数的值就相当于修改a的值

猜你喜欢

转载自blog.csdn.net/zhao3132453/article/details/82889571