首页 > 解决方案 > 我收到错误:重载“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;

标签: c++c++11c++14

解决方案


命名空间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);

推荐阅读