Invalid initialization of non-const reference of type

后端 未结 3 1986
深忆病人
深忆病人 2021-01-01 17:49

In the following code, I\'m not able to pass a temporary object as argument to the printAge function:

struct Person {
  int age;
  Person(int _a         


        
3条回答
  •  孤城傲影
    2021-01-01 18:14

    Simply make your print function take your argument by const&. This is also logically right as it doesn't modify your argument.

    void printAge(const Person &person) {
       cout << "Age: " << person.age << endl;
    }
    

    The actual problem is the other way around. You are passing a temporary(rvalue) to a function which expects an lvalue.

提交回复
热议问题