重载==用于与std :: string进行比较的类

Md.*_*man 3 c++ c++11

我想==为我的类重载运算符,以便我可以将我的类的属性与std :: string值进行比较.这是我的代码:

#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;
    // }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果字符串位于运算符的右侧,则它可以工作.但是如何重载==以使它在字符串位于运算符左侧时也能工作.

这里是 链接在ideone代码.

dav*_*ave 5

std::string作为第一个参数的运算符需要在类外:

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

您可能还想在类中Message::text private声明和声明运算符friend.

  • 我会使用`return m == s;`来确保一致性并避免逻辑重复. (3认同)