3

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.

D.Mendes
  • 159
  • 1
  • 11
Mahmudur Rahman
  • 640
  • 1
  • 6
  • 23
  • Most recently asked and answered here: https://stackoverflow.com/questions/53260752/how-to-multiply-integer-constant-by-fraction-object-in-c/53268504#53268504 Use a friend function to define the global binary operator. – Gem Taylor Nov 14 '18 at 10:42
  • note: in the ctor-initializer it should be `text(std::move(msg))` – M.M Nov 14 '18 at 12:01

1 Answers1

5

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.

perivesta
  • 3,417
  • 1
  • 10
  • 25