#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函數的開頭?
所有這些和更多是在任何[良好的C++書籍](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)解釋 – UnholySheep
「const」不是限定功能本身。它限定了返回類型。對於你提到的那些參數的潛在'const'也是一樣的,他們會限定這些參數的類型。成員函數限定符來到最後,像'void foo()const'。 –
你太過複雜了,只是返回'Type'而不是'const Type&' – acraig5075