Invalid initialization of non-const reference of type

后端 未结 3 1964
深忆病人
深忆病人 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 17:57

    Or, if you have a C++11-compliant compiler, can use the so called universal reference approach, which, via reference collapsing rules, can bind to both lvalue and rvalue references:

    #include <iostream>
    using namespace std;
    
    struct Person {
      int age;
      Person(int _age): age(_age) {}
    };
    
    template<typename T> // can bind to both lvalue AND rvalue references
    void printAge(T&& person) {
       cout << "Age: " << person.age << endl;
    }
    
    int main () {
      Person p(50);
      printAge(Person(50));  // works now
      printAge(p);
      return 0;
    }
    

    Or, in C++14,

    void printAge(auto&& person) {
       cout << "Age: " << person.age << endl;
    }
    
    0 讨论(0)
  • 2021-01-01 18:11

    Your code doesn't work if you run g++ or gcc compilers. You need to add const to void printAge(const Person &person). However, in Visual Studio it will work fine. I've tested for VS2010 and VS2012 and in both the following code works fine.

     #include<iostream>
    
    using namespace std;
    struct Person {
      int age;
      Person(int _age): age(_age) {}
    };
    
    void printAge(Person &person) {
       cout << "Age: " << person.age << endl;
    }
    
    int main () {
      Person p(50);
      printAge(Person(50));  // DOES NOT fail!
      printAge(p);
      return 0;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题