簡體   English   中英

使用const和非const返回引用重載函數

[英]Overloaded functions with const and non-const return references

請考慮以下代碼:

#include <cstdio>

struct X
{
    int a;
};

struct Y
{
    X x;

    X& GetX()
    {
        printf("non-const version\n");
        return x;
    }

    X const& GetX() const
    {
        printf("const version\n", __FUNCTION__);
        return x;
    }
};

int main()
{
    Y y;

    X& i = y.GetX();
    X const& j = y.GetX();

    return 0;
}

當在Code :: Blocks 16.01中運行時,我得到:

non-const version
non-const version

我經常在我工作的地方看到這樣的代碼,你在那里重載了具有不同返回類型的函數。 一個是參考,另一個是常量參考。

我的問題是:這種編碼的用途或好處是什么,如果const版本可以做的一切,非const版本也可以做到? 如何調用GetX()的const版本? 在上面的例子中,總是調用非const版本。

y是非const變量。 所以調用非const方法。

如果將y2定義為const,則會調用const方法。

int main()
{
    Y y;
    const Y y2 = y;

    X i = y.GetX();
    const X& j = y2.GetX();

    return 0;
}

暫無
暫無

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

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