您可以将临时对象传递给通过引用获取变量的函数吗? [英] Can you pass a temporary object to a function that takes a variable by reference?

查看:47
本文介绍了您可以将临时对象传递给通过引用获取变量的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解编译器错误时遇到问题.

I am having a problem understanding a compiler error.

在名为 rolo 的对象上调用的成员函数 add()通过引用引用一个 Card 变量:

The member function add() being called on an object named rolo takes a Card variable by reference:

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"));

对"Card"类型的非常量左值引用不能绑定到"Card"类型的临时对象.

Non-const lvalue reference to type 'Card' cannot bind to a temporary of type '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?

推荐答案

您不能将临时对象绑定到非常量左值引用( Card& card ).一种解决方案是将其作为 const左值引用传递:

You can't bind a temporary to a non-const lvalue reference (Card& card). One solution is to pass it as a const lvalue reference instead:

void add(Card const & card);

这篇关于您可以将临时对象传递给通过引用获取变量的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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