简体   繁体   English

您可以将临时对象传递给通过引用获取变量的函数吗?

[英]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.

相关问题 将临时对象传递给带指针的函数 - Pass temporary object to function that takes pointer 不能通过临时 object 作为参考 - Can't pass temporary object as reference 为什么可以通过引用为局部变量而不是临时变量返回函数? C ++ - Why Can you return a function by reference for a local variable and not for temporary variable? c++ 如果将匿名对象传递给需要引用的函数,C ++中会发生什么? - What happens in C++ if you pass an anonymous object into a function that takes a reference? C ++,为什么可以将右值传递给以左值引用为参数的函数 - C++, why can you pass rvalue to a function which takes lvalue reference as argument 将(临时?)std :: string传递给使用它来构造需要复制的对象的函数的最佳方法是什么? - What is the best way to pass a (temporary?) std::string to a function that uses it to construct an object that takes a copy? 您应该通过引用还是使用临时变量重载“=”运算符? - Should you overload the "=" operator by reference or with a temporary variable? 如何将临时对象作为非常量引用传递给成员函数? - How do I pass a temporary object as a non-const reference into a member function? 为什么接受引用的函数只能被赋予一个对象(而不是引用)? 是否会自动创建参考? - Why can a function which takes a reference be given just an object (and not a reference)? Is a reference automatically made? 通过引用传递一个 object function - Pass an object function by reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM