我有一个比较一对值的简单代码。我正在使用模板函数来减少代码量,所以我重载了函数两次(针对不同的情况)。
//cmp.h
template <class T>
bool cmp(T x,T y)
{
if(x == y)
{
return true;
}else
return false;
}
template <class T>
bool cmp(T *x,T *y)
{
if(*x==*y)
{ return true;}else
return false;
}
//main.cpp
#include <iostream>
#include <string>
#include "cmp.h"
using std::cout;
using std::endl;
using std::string;
int main() {
int aInt = 1, bInt = 2;
double aDouble = 3.0, bDouble = 3.0;
char aChars[5] = "haha", bChars[5] = "hahb";
char taChars[6] = "trick", tbChars[6] = "trick";
string aStr = "haha", bStr = "aha";
int* aIntPtr = &aInt, *bIntPtr = &bInt;
cout << cmp(aInt, bInt)<< endl;
cout << cmp(aDouble, bDouble)<< endl;
cout << cmp(aChars, bChars)<< endl;//i can't figure out why char prints out true here ???
cout << cmp(taChars, tbChars)<< endl;
cout << cmp(aStr, bStr)<< endl;
cout << cmp(aIntPtr, bIntPtr)<< endl;
cout << cmp(&aDouble, &bDouble) << endl;
return 0;
}
My output is:
0
1
1
1
0
0
1
And i expected:
0
1
0
1
0
0
1
为什么显示两个字符串相同?为什么如果我完全改变这个词,让我们说
char aChars[5] = "jack", bChars[5] = "hahb";
然后只有它给出正确的结果。我的第二个重载函数不应该处理这个问题吗? (bool cmp(T *x,T *y)
)
最佳答案
Why it shows that two strings are identical ?
因为
template <class T>
bool cmp(T *x,T *y)
{
if(*x == *y)
{
return true;
}else
return false;
}
仅检查 x
和 y
指向的第一个值。
所以当你检查
char aChars[5] = "haha", bChars[5] = "hahb";
cout << cmp(aChars, bChars)<< endl;//
检查 h
是否等于 h
。
如果你想检查字符串之间的相等性(如果你想避免使用旧的std::strcmp()
)你必须检查all字符直到第一个零。
但这对于旧式 C 字符串是正确的;我认为开发一个函数来检查泛型类型 T
的指针之间的相等性不是一个好主意。
-- 编辑 --
Could u guide me please
举个例子...很多时候我不认为在普通 C 中,但下面的东西应该可以工作
bool cmp (char const * p1, char const * p2)
{
for ( ; *p1 && *p1 == *p2 ; ++p1, ++p2 )
;
return *p1 == *p2;
}
题外话:你把代码写成
bool cmp(T *x,T *y)
{
if(*x==*y)
{ return true;}else
return false;
}
相当于
bool cmp(T *x,T *y)
{ return *x == *y; }
更一般地说......如果你有一个类型的代码
if ( someTest )
return true;
else
return false;
并且该函数返回一个bool
(或者someTest
是bool
类型),您可以编写(而且,恕我直言,更具可读性和优雅)简单地写
return someTest;
关于c++ - 模板函数重载。理解字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56474775/