繁体   English   中英

用运算符==结构重载

[英]Struct overloading with operator ==

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

#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 ,以便它可以访问私有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;
}

您最好对symbol对象有一个重载,而对char有一个重载:

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

在重载equal-to运算符时,将针对当前实例(即this )检查一个和唯一的参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM