簡體   English   中英

將返回值傳遞給引用調用的函數

[英]Passing return value to a function called 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;
}

在我的情況下,對象不是整數,而是具有許多內部變量和許多方法的類的實例。 有沒有辦法正確地做到這一點?

更新:通過不起作用,我的意思是我遇到了編譯錯誤:

file.cpp:32:28: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
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){ ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM