【问题标题】:no match for 'operator<' (operand types are 'const Vehicle' and 'const Vehicle')'operator<' 不匹配(操作数类型为 'const Vehicle' 和 'const Vehicle')
【发布时间】:2022-01-06 00:29:45
【问题描述】:

我有这门课:

class Vehicle {
    private:
        char dir_;
    public:
        char car_;
        // functions
        // 
        // overloaded operators
        bool operator==(Vehicle&);
        bool operator<(const Vehicle& v);
        //
        // other functions
    
};

有这个实现:

bool Vehicle::operator<(const Vehicle& v) {
    return (car_ < v.car_);
}

我收到了这个错误: “'operator

在“stl_funxtion.h”中

【问题讨论】:

  • 你需要声明operator&lt;const
  • 请显示minimal reproducible example。不知道你是如何在“stl_function.h”中得到错误的。

标签: c++ class c++17


【解决方案1】:

要使函数在const 对象上可用,您需要声明该函数const

class Vehicle {
      ⋮
    bool operator<(const Vehicle& v) const;
      ⋮                              ^^^^^
      ⋮
};

bool Vehicle::operator<(const Vehicle& v) const {
      ⋮                                   ^^^^^
}

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 2021-04-20
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2017-10-13
    相关资源
    最近更新 更多