2017-04-04 89 views
0

考慮下面的代碼:用const和non-const的回報重載函數引用

#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; 
} 

當代碼:: Blocks的16.01跑,我得到:

non-const version 
non-const version 

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

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

+1

函數重載不考慮返回類型。 –

+3

嘗試製作'y' const –

+0

如果你只有一個const值,該怎麼辦? –

回答

0

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

如果將y2定義爲const,它將調用const方法。

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

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

    return 0; 
}