将返回值传递给引用调用的函数

时间:2015-10-25 00:44:59

标签: c++ return-value pass-by-reference

我有一个可以处理自定义类型(类)对象的函数。 为了避免复制该对象,我想让我的函数通过引用来使用它。

这适用于由代码创建的对象,但对于由方法返回的相同类型的对象,它不会。

这是一个带整数的简单示例,其中areEqual是函数:

#include <iostream>
using namespace std;

class part
{
    int i_Nbr;
    public:
    part(int n){
        i_Nbr = n;
    }
    int getNbr(){
        return i_Nbr;
    }
};

bool areEqual(int& q1, int& q2){
    return q1==q2;
}

int main(){
    int i1 = 50;
    int i2 = 60;
    part a(240);
    part b(220);
    bool eq;

    // this works
    eq = areEqual(i1, i2 );
    cout << eq << endl;

    // but this doesn't
    eq = areEqual(a.getNbr(), b.getNbr() );
    cout << eq << endl;

    return 0;
}

在我看来,对象不是整数,而是具有许多内部变量和许多方法的类的实例。 有没有办法正确地做到这一点?

更新 by不起作用我的意思是我遇到了编译错误:

file.cpp:32:28: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

1 个答案:

答案 0 :(得分:2)

bool eq = areEqual(a.getNbr(), b.getNbr() );

不起作用,因为函数返回int,这是areEqual调用中的临时对象。参数类型为int&时,无法使用临时对象。在int const&中使用areEqual作为参数类型,或仅使用int

bool areEqual(int const& q1, int const& q2){ ... }

bool areEqual(int q1, int q2){ ... }
相关问题