C++ 重载==用于将类与std::string进行比较

C++ 重载==用于将类与std::string进行比较,c++,c++11,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 {

我想为我的类重载
==
运算符,以便我可以将类的属性与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;
    // }
}
#包括
#包括
使用名称空间std;
类消息
{
公众:
字符串文本;
消息(字符串消息):文本(消息){}
布尔运算符==(常量字符串&s)常量{
返回s==文本;
}
};
int main()
{
字符串a=“a”;
信息aa(a);
如果(aa==a){

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

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

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

最近的问题和回答如下:使用friend函数定义全局二进制运算符。注意:在ctor初始值设定项中,它应该是
text(std::move(msg))
我会使用
返回m==s;
来确保一致性并避免逻辑重复。@Jarod42好主意,我更改了它!