Overload == for class to compare with std::string

Viewed 126

I want to overload == operator for my class so that I can compare a property of my class with a std::string value. Here is my code:

#include <iostream>
#include <string>
using namespace std;

class Message
{
public:
    string text;
    Message(string msg) :text(msg) {}
    bool operator==(const string& s) const {
        return s == text;
    }
};

int main()
{
    string a = "a";
    Message aa(a);
    if (aa == a) {
        cout << "Okay" << endl;
    }
    // if (a == aa) {
    //    cout << "Not Okay" << endl;
    // }
}

Now, it works if the string is on the right side of the operator. But how to overload == so that it also works if the string is on the left side of the operator.

Here is link of the code in ideone.

1 Answers

The operator with std::string as first parameter needs to be outside the class:

bool operator==(const std::string& s, const Message& m) {
    return m == s; //make use of the other operator==
}

You may also want to make Message::text private and declare the operator as friend in the class.

Related