在下面的代码中,我无法将一个临时对象作为参数传递给
printAge
函数: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)); // fails!
printAge(p);
return 0;
}
我收到的错误是:
error: invalid initialization of non-const reference of type ‘Person&’ from an rvalue of type ‘Person’
我意识到这与将lValue传递给期望rValue的函数有关...是否有办法通过使用std::move或其他方式将我的lValue转换为rValue?我尝试使用常量参数,但似乎不起作用。
const
左值引用来代替。 - juanchopanza