c++ - 反正有没有覆盖内置函数?在 C++ 中
问题描述
所以我试图覆盖函数 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
自己。std::max
from#include<algorithm>
已经做了你想做max
的事情(只是它处理了一些你没有考虑的边缘情况)。
只需使用std::max
(或max
之后using std::max;
),不要定义自己的实现。
推荐阅读
- c++ - 为什么 ## aka 标记粘贴运算符不适用于 C 和 C++ 中的注释?
- typo3 - femanager - 如何将注册发送到特殊页面(而不仅仅是活动页面)
- javascript - 每个帖子下的 Gatsby 网站上一个和下一个链接
- google-bigquery - BigQuery 中缺少的airline_ontime_data 和weather_geo(应该在样本下)在哪里?
- javascript - vue过滤列表点击
- windows - 在批处理文件的 for 循环中使用关系运算符
- r - 如何在 R 中转换数据集?
- react-native - 在反应原生博览会中上传二进制图像
- django - 如何在 Django 中将数字转换为月份名称?
- reactjs - 从 DynamoDB 表中获取数据并将其显示在 React 应用程序中