首页 > 解决方案 > 反正有没有覆盖内置函数?在 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);

它给了我错误

标签: c++c++14c++17

解决方案


max不是内置函数,它是标准库的一部分。您不是试图覆盖/替换它,您只是添加另一个函数重载,将在重载解析期间考虑并且会使调用模棱两可,因为您的重载和您使用导入的标准库的重载都using namespace std;将匹配。

您的问题是您正在使用using namespace std;,它将标准库名称空间中的所有std::名称导入全局名称空间。

这被认为是不好的做法,因为它会导致像您这样的问题。

从标准库命名空间中删除using namespace std;并始终使用 为名称添加前缀std::,例如std::cout,或者仅导入选定的名称列表,例如:

using std::cout;

但是,没有理由定义max自己。std::maxfrom#include<algorithm>已经做了你想做max的事情(只是它处理了一些你没有考虑的边缘情况)。

只需使用std::max(或max之后using std::max;),不要定义自己的实现。


推荐阅读