2017-10-18 70 views
-6
#include <iostream> 
#include <string> 
using namespace std; 

template <typename Type> 
const Type& GetMax(Type& value1,Type& value2) 
{ 
    if(value1 > value2) 
     return value1; 
    else 
     return value2; 
} 
template<typename Type> 
void DisplayComparison(const Type& value1,const Type& value2) 
{ 
    cout<<"GetMax("<<value1<<","<<value2<<") = "; 
    cout<<GetMax(value1,value2)<<endl; 
} 
int main() 
{ 
    int Int1 = -102, Int2 = 2001; 
    DisplayComparison(Int1,Int2); 

    double d1 = 3.14,d2 = 3.1416; 
    DisplayComparison(d1,d2); 

    string Name1("Jack"),Name2("John"); 
    DisplayComparison(Name1,Name2); 

    return 0; 
} 

const Type& GetMax ...是const是必要的嗎?如果是,爲什麼? 如果我這樣寫 - >const Type& GetMax(const Type& value1,const Type& value)那兩個const在做什麼? :(爲什麼我們需要將const放在GetMax函數的開頭?

+4

所有這些和更多是在任何[良好的C++書籍](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)解釋 – UnholySheep

+0

「const」不是限定功能本身。它限定了返回類型。對於你提到的那些參數的潛在'const'也是一樣的,他們會限定這些參數的類型。成員函數限定符來到最後,像'void foo()const'。 –

+0

你太過複雜了,只是返回'Type'而不是'const Type&' – acraig5075

回答

0

我要提出幾點關於常量,這樣你的時候,什麼可以根據需要使用它是明確的:

案例1:GetMax(const Type value1)

這裏值1是一個本地副本,我能想到幾個百分點

我能想到的有幾個原因:

1)當有人讀取代碼,看看const Type value1,他們知道value1不應在體內被修改功能。

2)編譯器會告訴你什麼時候你試圖在函數的主體中修改value1。因此,添加const可以防止錯誤。

3)但是,在C++ 11中還有另一個區別。當移動操作修改對象時,不能移動常量對象。因此,您只能在功能體中複製value1,並且無法從中移動。 4)另外,如果這是一個類類型,你不能在一個const對象上調用非const成員函數。

案例2:GetMax(const Type& value1)

我們不知道如何value1使用功能之外,所以我們要保護它不被修改。

案例3:const Type& GetMax()

談到const函數之前,意味着它會返回一個const參考Type(這裏GetMax

拿這個例子:

Class xyz; 
Type& t = xyz.GetMax()   //This is INCORRECT 
const Type& tc = xyz.GetMax() //This is OKAY! 

所以,總結一下,除非你有上述要求,否則你不需要使用const,儘管這樣做可能是一種好的做法。在幾種情況下。