作为返回类型"const int&"做什么?

What does "const int&" do as a return type?

本文关键字:什么 const 返回类型 int      更新时间:2023-10-16
const int& max(int a[], int length)
{
int i=0;
    for(int j=0; j<length; j++)
        if(a[j]>a[i]) i=j;
    return a[i];
}
int main(){
    int array[] = {12, -54, 0, 123, 63};
    int largest;
    largest = max(array,5);
    cout<< "Largest element is " << largest << endl;
    return 0;
}

所以我的问题是," const int&amp;作为返回类型?为什么我在函数期望参考时返回值?

通常,返回参考可以避免复制返回值,并且(如果不是 const qualified(使您有机会更改"原始"值。返回类型const T&通常与类类型的对象结合使用,例如std::vector,复制可能导致(不需要的(开销。但是,与int这样的基本数据类型结合使用,传递const int&可能比复制原始INT值更开销。

此外,在您的示例中,如果将const int&类型的结果分配给非参考类型,例如 int largest = max(...),返回值是"重新推荐"的,并按值分配。因此,您可以更改变量的内容,因为它是const参考值的副本。如果您具有const int&类型,并且将其分配给类型const int&的变量,则可以获得参考,但是编译器将不允许您更改其内容。

因此,唯一没有int引用的内容是没有const,然后您将允许您更改" Origninal"值的内容。请参阅以下代码;希望它有所帮助:

int& max(int a[], int length) {
    return a[3];
}
const int& maxConst(int a[], int length) {
    return a[3];
}
int main(){
    int array[] = {12, -54, 0, 123, 63};
    int largest = max(array,5);
    cout<< "Largest element (value) is " << largest << endl;
    largest = 10;
    cout << "Element at pos 3 is: " << array[3] << endl;
    int largestConst = maxConst(array,5);
    cout<< "Largest element (value) is " << largestConst << endl;
    largestConst = 10;
    cout << "Element at pos 3 is: " << array[3] << endl;
    int &largestRef = max(array,5);
    cout<< "Largest element (ref) is " << largestRef << endl;
    largestRef = 10;
    cout << "Element at pos 3 is: " << array[3] << endl;
    const int &largestRefConst = maxConst(array,5);
    cout<< "Largest element (value) is " << largestRefConst << endl;
    // largestRefConst = 10;  // -> cannot assign to variable with const-qualified type
    //cout << "Element at pos 3 is: " << array[3] << endl;
    return 0;
}

输出:

Largest element (value) is 123
Element at pos 3 is: 123
Largest element (value) is 123
Element at pos 3 is: 123
Largest element (ref) is 123
Element at pos 3 is: 10
Largest element (value) is 10