【问题标题】:Why does this code have no match for operator error? [duplicate]为什么此代码与操作员错误不匹配? [复制]
【发布时间】:2019-12-17 18:03:12
【问题描述】:

我在测试中遇到过这个问题,不知道为什么会产生错误。

#include <iostream>
#include <string.h>
using namespace std;

template<typename T>
T Min(T a, T b)
{
    if (a <= b)
        return a;
    else
        return b;
}

class A
{
public:
    int n;
    A(int n = 0) : n(n) {}
};

int main()
{
    A a1(2), a2(1);
    cout << Min(a1, a2).n;
    return 0;
}

我尝试输入并运行它,其中一条错误消息是这样的。

error: no match for 'operator<=' (operand types are 'A' and 'A')

为什么会这样?如果有人能解释一下,将不胜感激,谢谢!

【问题讨论】:

    标签: c++ class c++11 templates operator-overloading


    【解决方案1】:

    因为class A 没有用于比较的运算符,您可能打算这样做:

    if(a.n <= b.n)
    

    或者,定义缺少的运算符以使其工作:

    bool operator<=(A const& a, A const& b)
    {
        return a.n <= b.n;
    }
    

    【讨论】:

      【解决方案2】:

      A 是用户定义的类型,因此您需要定义relational operators 来比较其对象。

      例如

      bool operator< (const A& lhs, const A& rhs) { return lhs.n < rhs.n; }
      bool operator> (const A& lhs, const A& rhs) { return rhs < lhs; }
      bool operator<=(const A& lhs, const A& rhs) { return !(lhs > rhs); }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-03
        • 1970-01-01
        • 2014-11-23
        • 2018-03-21
        • 2019-11-17
        • 2020-07-27
        相关资源
        最近更新 更多