我的教授給了我這個任務。函數模板中的邏輯錯誤
實現所謂 最大的通用功能,這需要通用 類型的3個參數,並返回最大這些 3.實現專門功能的char *類型。
這是我的代碼:
#include <iostream>
#include <string>
using namespace std;
template<typename T>
T Max(T first,T second,T third)
{
if(first > second)
{
if(first > third)
{
return first;
}
else
{
return third;
}
}
else if(second > third)
{
return second;
}
else
{
return third;
}
}
template<>
char* Max(char* first,char* second,char* third)
{
if(strcmp(first, second) > 0)
{
if(strcmp(first, third) > 0)
{
return first;
}
else
{
return third;
}
}
else if(strcmp(second, third) > 0)
{
return second;
}
else
{
return third;
}
}
int main(void)
{
cout << "Greatest in 10, 20, 30 is " << Max(10, 20, 30) << endl;
char a = 'A';
char b = 'B';
char c = 'C';
char Cptr = *Max(&a, &b, &c);
cout << "Greatest in A, B ,C is " << Cptr << endl;
string d = "A";
string e = "B";
string f = "C";
string result = *Max(&d, &e, &f);
cout << "Greatest in A, B, C is " << result << endl;
}
輸出:
最大在10,20,30是30
最大在甲 ,B,C是C
A,B,C最大是 A
問題:
如果我在max函數一通char數據類型,B,C,它返回C,但是如果我傳遞字符串數據類型A,B,C,返回A.
爲什麼它在這裏返回A嗎?
感謝您的幫助。 – Searock 2010-10-12 08:56:00