C ++ - lvalue required as left assignment operand

Consider the following code:

#include <iostream>
using namespace std;

class X 
{
    int i;
public:  
    X(int ii = 0);
};

X::X(int ii) { i = ii; }

int a;

X f1() { return X(); }
int f2() { return a; }

int main() {
    f1() = X(1);
    f2() = 3;
} 

If you try to run it, you will get

error: lvalue required as left assignment operand

on line 17, therefore

f1 ()

considered lvalue, and

2 ()

no. An explanation will be of great help in how this will work.

+4
source share
2 answers

f1() considered lvalue

, , f1, rvalue ( , f2, prvalue). f1() = X(1); f1().operator=(X(1));, , ; , f1(), . , - rvalue .

, ; . , lvalue.

+5

f1() rvalue. (lvalue),

int f2() { return a; }

int& f2() {  return a; }
   ^

f1() rvalue, f1() = X(1); f1().operator=(X(1));, .

.

+1

Source: https://habr.com/ru/post/1684528/


All Articles