Reputation: 2784
I writing algorithm for converting roman to integer (Code below) and I got error 'too many parameters for this function', but I need two parameters for my comparison. Does someone know how fix my code?
#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;
}
Upvotes: 0
Views: 133
Reputation: 780724
The left parameter of the operator is the automatic this
object, you don't need to specify both parameters in the parameter list.
bool operator== (char& a) {
return a == upperCase;
}
However, this only allows for symbol == char
, not char == symbol
. For the latter, you need a regular function, not a member function. You'll need to declare this as a friend
of Solution
so it can access the private symbol
class.
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;
}
Upvotes: 3
Reputation: 10047
You'd be better have one overload for symbol
objects, and another for char
's:
bool operator ==(symbol& b)
{
return (b.upperCase==upperCase);
}
bool operator ==(char& a)
{
return a == upperCase;
}
In overloading the equal-to operator, the one and only argument is checked against the current instance (i.e. this
).
Upvotes: 2