使用类重载运算符==与std::string进行比较

3

我希望能够为我的类重载==运算符,以便我可以将我的类的属性与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;
    // }
}

现在,如果字符串在运算符右侧,它就可以工作。但如何重载==以使其在字符串位于运算符左侧时也起作用?
这里是ideone上代码的链接

最近在此处提问和回答:https://stackoverflow.com/questions/53260752/how-to-multiply-integer-constant-by-fraction-object-in-c/53268504#53268504 使用友元函数定义全局二元运算符。 - Gem Taylor
请注意:在构造函数初始化列表中应该是 text(std::move(msg)) - M.M
1个回答

5

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

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

您可能还想将Message::text设置为private,并在类中声明运算符为friend


3
为了确保一致性并避免逻辑重复,我会使用 return m == s; - Jarod42
@Jarod42 好主意,我改了! - perivesta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接