[英]Can you pass a temporary object to a function that takes a variable by reference?
I am having a problem understanding a compiler error.我在理解编译器错误时遇到问题。
The member function add()
being called on an object named rolo
takes a Card
variable by reference:在名为
rolo
的对象上调用的成员函数add()
通过引用获取Card
变量:
class Card{
public:
Card(string first,string last,string occupation,string address,string phoneNum);
};
class Rolodex{
public:
void add(Card& card);
};
int main()
{
Rolodex rolo;
rolo.add(Card("Tony", "Hansen", "Writer", "12 E. St. NY, NY 33333", "555-9999"));
}
The compiler is giving me an error on this line:编译器在这一行给了我一个错误:
rolo.add(Card("Tony", "Hansen", "Writer", "12 E. St. NY, NY 33333", "555-9999"));
Non-const lvalue reference to type 'Card' cannot bind to a temporary of type 'Card'.
对“Card”类型的非常量左值引用不能绑定到“Card”类型的临时变量。
I don't think that it is legal to call the method with a temporary object as argument.我认为以临时对象作为参数调用该方法是不合法的。 I think it is better if the following is done instead:
我认为如果改为执行以下操作会更好:
Card variable("Tony", "Hansen", "Writer", "12 E. St. NY, NY 33333", "555-9999");
rolo.add(variable);
Why is the error happening?为什么会发生错误? Is there a way to fix it?
有办法解决吗?
You can't bind a temporary to a non-const lvalue reference ( Card& card
).您不能将临时值绑定到非常量左值引用(
Card& card
)。 One solution is to pass it as a const lvalue reference instead:一种解决方案是将其作为const 左值引用传递:
void add(Card const & card);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.