C++关于‘&’的有关问题,不知问什么程序会冒那样的异常的提醒,求大牛
C++关于‘&’的问题,不知问什么程序会冒那样的错误的提醒,求大牛啊
Type min(Type &a,Type &b)改为Type min(Type a,Type b)后在main中的min显示有多个重载函数
将“if(strcmp(&a,&b))”改为if(strcmp(a,b))就显示示const形参与实参不兼容
真心求助啊,万分感谢
代码如下:
#include"stdafx.h"
#include"iostream"
using namespace std;
template<class Type>
Type min(Type &a,Type &b)
{
if(a<b)
return a;
else
return b;
}
char min(char a,char b)
{
if(strcmp(&a,&b))
return b;
else
return a;
}
void main()
{
cout<<"最小值"<<min(10,1)<<endl;
cout<<"最大值"<<max('a','b')<<endl;
}
------解决思路----------------------
char 比较也可以使用 < 来比较。
不需要特化。缺省模板函数就可以了。
但是字符串就需要使用 strcmp
------解决思路----------------------
改成Type min(Type a,Type b)是OK的,不过最好不要写这么近义的重载函数
strcmp(&a,&b)这样是很危险的,因为他们都没有NULL结束符
------解决思路----------------------
参考C++里实现。
------解决思路----------------------
http://en.cppreference.com/w/cpp/algorithm/min
------解决思路----------------------
const T& 是关键
Type min(Type &a,Type &b)改为Type min(Type a,Type b)后在main中的min显示有多个重载函数
将“if(strcmp(&a,&b))”改为if(strcmp(a,b))就显示示const形参与实参不兼容
真心求助啊,万分感谢
代码如下:
#include"stdafx.h"
#include"iostream"
using namespace std;
template<class Type>
Type min(Type &a,Type &b)
{
if(a<b)
return a;
else
return b;
}
char min(char a,char b)
{
if(strcmp(&a,&b))
return b;
else
return a;
}
void main()
{
cout<<"最小值"<<min(10,1)<<endl;
cout<<"最大值"<<max('a','b')<<endl;
}
------解决思路----------------------
char 比较也可以使用 < 来比较。
不需要特化。缺省模板函数就可以了。
但是字符串就需要使用 strcmp
template<class Type>
Type min_(Type a, Type b)
{
if (a<b)
return a;
else
return b;
}
template< >
char const *min_(char const *a, char const *b)
{
if (strcmp(a, b))
return b;
else
return a;
}
template< >
wchar_t const *min_(wchar_t const *a, wchar_t const *b)
{
if (wcscmp(a, b))
return b;
else
return a;
}
------解决思路----------------------
改成Type min(Type a,Type b)是OK的,不过最好不要写这么近义的重载函数
strcmp(&a,&b)这样是很危险的,因为他们都没有NULL结束符
------解决思路----------------------
参考C++里实现。
template<class T>
const T& min(const T& a, const T& b)
{
return (b < a) ? b : a;
}
------解决思路----------------------
http://en.cppreference.com/w/cpp/algorithm/min
------解决思路----------------------
const T& 是关键