类型的非const引用的初始化无效 [英] Invalid initialization of non-const reference of type

查看:974
本文介绍了类型的非const引用的初始化无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我无法将临时对象作为参数传递给 printAge 函数:

  struct Person {
int age;
Person(int _age):age(_age){}
};

void printAge(Person& person){
cout<< 年龄:< person.age<< endl;
}

int main(){
Person p(50);
printAge(Person(50)); // failed!
printAge(p);
return 0;
}

我得到的错误是:

 错误:从类型'Person'的右值初始化类型为'Person&'的非const引用
pre>

我意识到这是与传递一个lValue到一个函数,期望一个rValue ...有一种方法来转换我的值为rValue通过使用std ::移动还是什么?

解决方案

只需让你的打印函数接受你的参数 const& 。这也是逻辑上正确的,因为它不会修改你的参数。

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

实际的问题是相反的。您正在传递一个临时(rvalue)到一个函数,期望一个左值。


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 _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;
}

The error I get is:

error: invalid initialization of non-const reference of type ‘Person&’ from an rvalue of type ‘Person’

I realize that this is something to do with passing an lValue to a function expecting a rValue... Is there a way to convert my lValue to rValue by using std::move or something? I tried taking a constant parameter, but that does not seem to work.

解决方案

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.

这篇关于类型的非const引用的初始化无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆