c++ - 使用运算符 == 的结构重载

标签 c++ struct operator-overloading

我编写了将 roman 转换为整数的算法(下面的代码),但出现错误“此函数的参数过多”,但我需要两个参数进行比较。有人知道如何修复我的代码吗?

#include <iostream>
using namespace std;

int main() {
  class Solution {
  private:
    struct symbol {
      char upperCase;
      char lowerCase;
      bool operator ==(char& a, symbol& b) { // ERROR: too many parametres for this function 
        return a == b.upperCase;
      };
    };
    const symbol one {'I', 'i'};
    // ...
    const symbol thousand {'M', 'm'};
  public:
    int romanToInt(string s) {
    // ...
    }
  };
  return 0;
}

最佳答案

运算符左边的参数是自动生成的this对象,不需要在参数列表中同时指定这两个参数。

bool operator== (char& a) {
    return a == upperCase;
}

但是,这只允许 symbol == char,而不是 char == symbol。对于后者,您需要一个常规函数,而不是成员函数。您需要将其声明为 Solutionfriend,以便它可以访问私有(private) symbol 类。

  class Solution {
  private:
    struct symbol {
      char upperCase;
      char lowerCase;
      bool operator ==(const char& a) { // ERROR: too many parametres for this function 
        return a == upperCase;
      };
    };
    const symbol one {'I', 'i'};
    // ...
    const symbol thousand {'M', 'm'};
  public:
    int romanToInt(string s) {
    // ...
    }
    friend bool operator==(const char&, const symbol&)
  };

bool operator==(const char&a, const Solution::symbol& b) {
  return a == b.uppercase;
}

关于c++ - 使用运算符 == 的结构重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49127159/

相关文章:

c++ - 在C++的编译时初始化派生结构类型的变量

c++ - 将 float 转换为 int,还是将 int 转换为 float?

c++ - const-ness 作为模板参数

c++ - Boost String Replace 不会用字符串替换换行符

c - C中struct的双指针是什么意思

C++:模板类二元运算符重载 - 段错误?

c++ - 是否可以将 if 语句基于构造函数?

c++ - 包括多个动态数组的 c-struct 的分配

c - 用于字符数组和结构的 Malloc

c++ - 为枚举类覆盖 C++20 宇宙飞船运算符