c++ - 我收到错误:重载“max(Cents&, Cents&)”的调用不明确
问题描述
1 ..我正在测试以下使用模板
的代码源代码来自这个learncpp教程
https://www.learncpp.com/cpp-tutorial/132-function-template-instances/
#include <iostream>
#include <cstring>
#include <typeinfo>
using namespace std;
// ======================================================================
template <typename T>
const T& max(const T& x,const T& y)
{
return (x>y)?x:y;
}
// ======================================================================
class Cents
{
private:
int m_cents;
public:
Cents(int cents):m_cents(cents)
{
}
friend bool operator>(const Cents &c1,const Cents &c2)
{
return (c1.m_cents>c2.m_cents);
}
int get_val()
{
m_cents;
}
};
// ======================================================================
int main()
{
Cents nickle(5);
Cents dime(10);
Cents bigger=max(nickle,dime);
// std::cout<<"bigger: "<<bigger.get_val()<<std::endl;
// bigger: 1471225424
return 0;
}
我得到这个错误
error: call of overloaded ‘max(Cents&, Cents&)’ is ambiguous
Cents bigger=max(nickle,dime);
代码有什么问题?
2.. 我怎样才能打印结果?
例如,我试过std::cout<<"bigger: "<<bigger<<std::endl;
但我遇到了以下错误,说没有重载运算符 << for large(Cent type object)
error: cannot bind ‘std::basic_ostream<char>’ lvalue to ‘std::basic_ostream<char>&&’
std::cout<<"bigger: "<<bigger<<std::endl;
error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream<char>’ and ‘Cents’)
std::cout<<"bigger: "<<bigger<<std::endl;
解决方案
命名空间std
还包含一个名为的函数模板max
,其签名与您的max
函数模板基本相同。虽然您没有明确包含std::max
正式定义的标头 ( <algorithm>
),但实现可能包含来自任何其他库标头[res.on.headers]/1的任何库标头,因此它是完全合法的(以及使用标准库必须期望处理)std::max
最终std
在您的情况下在命名空间中声明。这
using namespace std;
顶部的指令然后将std::max
函数模板引入全局命名空间。因此,在这个 using 指令之后的任何时候,非限定名称查找都会找到两个max
在全局命名空间中命名的函数模板,它们具有相同的签名,因此,您的调用max
将是模棱两可的(无法决定应该调用哪个函数,因为它们'都是同样有效的选择)。要解决此问题,请摆脱(推荐)或通过限定名称using namespace std;
显式识别函数调用的目标,例如:max
Cents bigger = ::max(nickle, dime);
推荐阅读
- php - PhpMyAdmin 连接
- django - HTTPS 协议不适用于 ec2 实例上的 django 和 nginx
- r - R中的滚动加权平均值(多个观察值)
- google-sheets - Google表格:检查列,匹配单元格,返回相邻单元格的公式
- python-3.x - 引发序列化错误
- search - 没有 RegEx 的 Mongoose 部分字段搜索
- node.js - 如何使用 botbuilder SDK V4 for node.js 为我的机器人添加提示的 maxRetries
- artifactory - 使用 RPM 安装后 Artifactory 配置文件在哪里?
- c# - 在 C# 的 IEqualityComparer 中使用泛型
- exception-handling - 在运行时异常的情况下,如何从 Apache Flink 中的函数手动重放元组?