c++ - 运算符重载中没有运算符 '==' 匹配

标签 c++ struct operator-overloading overloading

<分区>

我正在研究“Roman to int”算法,我的代码如下。我得到一个错误:

no operator "==" matches these operands -- operand types are: char == const Solution::symbol.

有人可以帮我修复代码吗?

// solution.h
#include <string>
using namespace std;

class Solution {
  private:
    struct symbol {
      char upperCase;
      char lowerCase;
      bool operator ==(char ch) {
        return ch == upperCase || ch == lowerCase;
      };
    };
    static constexpr symbol one {'I', 'i'};
    static constexpr symbol five {'V', 'v'};
    static constexpr symbol ten {'X', 'x'};
    static constexpr symbol fifty {'L', 'l'};
    static constexpr symbol hundred {'C', 'c'};
    static constexpr symbol fiveHundred {'D', 'd'};
    static constexpr symbol thousand {'M', 'm'};
  public:
    bool romanToInt() {
      char ch = 'I';
      ch == one; // ERROR: no operator "==" matches these operands -- operand types a re: char == const Solution::symbol
      one == ch; // ERROR: no operator "==" matches these operands -- operand types a re: const Solution::symbol == char
    };
};

// main.cpp
#include <iostream>
#include "../Header Files/solution.h"
using namespace std;

int main() {
  Solution solution;
  solution.romanToInt();

  return 0;
}

最佳答案

至少要像这样声明运算符

  bool operator ==(char ch) const {
    return ch == upperCase || ch == lowerCase;
  };

并使用

return one == ch;

关于c++ - 运算符重载中没有运算符 '==' 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49130368/

相关文章:

c++ - 在抛出 'std::out_of_range' what(): basic_string::substr 实例后终止调用

c++ - 各种类型的容器 - C++

vector - 如何创建 Vec<Struct> 并将其附加到 Vec<Struct>?

c++ - 以下小于(<)运算符对于什么类型 T 是合法的?

c++ - 函数对象如何影响重载决议?

C++:如何提高经常被复制的自定义类的性能?

go - 渲染 html 模板 golang revel

c - 从结构数组中输出随机元素

c++ - 集合中的不可变对象(immutable对象)(C++ 和 Qt)

c++ - 运算符++ : reference vs value return and unused argument