我的教授给了我这个任务。
实现一个名为 Max 的泛型函数,它接受 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 A、B、C 中
最伟大的是 A、B、C 中最伟大的是 A
问题 :
如果我在 Max 函数 A、B、C 中传递 char 数据类型,它返回 C,但如果我传递字符串数据类型 A、B、C,它返回 A。
为什么它在这里返回 A?