我编写了将 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
。对于后者,您需要一个常规函数,而不是成员函数。您需要将其声明为 Solution
的 friend
,以便它可以访问私有(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/