所以我试图覆盖函数max我遇到了很多错误
> call of overloaded 'max(int&, int&)' is ambiguous
> /usr/include/c++/7/bits/stl_algobase.h:219:5: note: candidate: constexpr const _Tp& std::max(const _Tp&, const _Tp&) [with _Tp = int]
max(const _Tp& __a, const _Tp& __b)
>
> In file included from /usr/include/c++/7/bits/char_traits.h:39:0,
from /usr/include/c++/7/ios:40,
from /usr/include/c++/7/ostream:38,
from /usr/include/c++/7/iostream:39,
from prog.cpp:1:
我的代码:
#include<iostream>
using namespace std;
template <typename T>
T max(T a, T b)
{
return a > b?a:b;
}
int main()
{
cout<< max(5,4);
return 0;
}
有没有办法覆盖内置函数或预定义函数?
即使我申报
int a(5),b(4);
cout<<max(a,b);
它给我错误
max
不是内置函数,它是标准库的一部分。您并没有试图覆盖/替换它,您只是添加了另一个函数重载,该重载将在重载解析过程中考虑,并且会使调用变得不明确,因为您的重载和使用using namespace std;
导入的标准库重载都将匹配。
您的问题是使用using namespace std;
,它将所有名称从标准库名称空间std::
导入全局名称空间。
这被认为是不好的做法,正是因为它会引起像你这样的问题。
删除using namespace std;
,而不是始终用std::
作为标准库名称空间中名称的前缀,例如std::cout
,或者只导入选定的名称列表,例如:
using std::cout;
但是,没有理由自己定义max
。#include<algorithm>
中的std::max
已经完成了您希望max
执行的操作(只是它处理了一些您没有考虑的边缘情况(。
只需使用std::max
(或using std::max;
之后的max
(,不要定义自己的实现。