簡體   English   中英

錯誤:從 int 類型的右值初始化 int& 類型的非常量引用無效

[英]error: invalid initialization of non-const reference of type int& from an rvalue of type int

在下面的代碼中,當我將idxsum作為參考時,它顯示給定的錯誤。 如果我在沒有參考的情況下使用idxsum ,它工作正常。 為什么?

void func(int &idx, int &sum, vector<int> &arr, int N, vector<int> &res)
{   
    if(idx == N)
    {
        res.push_back(sum);
        return;
    }
    // pick the element
    func(idx + 1, sum+arr[idx], arr, N, res);
    
    // not pick the element
    func(idx + 1, sum, arr, N, res);
}

vector<int> subsetSums(vector<int> arr, int N)
{
    // Write Your Code here
    int idx = 0;
    int sum = 0;
    vector<int> res;
    func(idx, sum, arr, N, res);
    sort(res.begin(), res.end());
    return res;
}

idx + 1是臨時的,它沒有地址,因此不能綁定到引用。 sum+arr[idx]也是如此。

const用於僅輸入參數可能是個好主意。 因為const int&可以綁定到臨時對象。 雖然沒有理由通過常量引用來傳遞整數類型,但通過值傳遞是可以的。

您遞歸調用func並將idx + 1作為第一個參數傳遞,但idx + 1不能是左值引用,只能是右值,因為它是一個臨時值。

暫無
暫無

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

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