所以我试图覆盖函数 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:
Run Code Online (Sandbox Code Playgroud)
我的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法覆盖内置函数或预定义函数?
即使我声明
int a(5),b(4);
cout<<max(a,b);
Run Code Online (Sandbox Code Playgroud)
它给了我错误
max不是内置函数,它是标准库的一部分。您并不是要覆盖/替换它,您只是添加了另一个将在重载解析期间考虑的函数重载,并且会使调用变得模棱两可,因为您的重载和使用 导入的标准库的重载都using namespace std;将匹配。
您的问题是您正在使用using namespace std;,它将标准库命名空间中的所有名称std::导入到全局命名空间中。
这被认为是不好的做法,因为它会导致像您这样的问题。
using namespace std;从标准库命名空间中删除并改为始终使用 前缀名称std::,例如std::cout,或仅导入选定的名称列表,例如:
using std::cout;
Run Code Online (Sandbox Code Playgroud)
但是,没有理由定义max自己。std::maxfrom#include<algorithm>已经完成了你想做max的事情(只是它处理了一些你没有考虑的边缘情况)。
只需使用std::max(或max之后using std::max;),不要定义自己的实现。
| 归档时间: |
|
| 查看次数: |
68 次 |
| 最近记录: |