gpt4 book ai didi

c++ - 为类重载 == 以与 std::string 进行比较

转载 作者:太空狗 更新时间:2023-10-29 20:33:45 25 4
gpt4 key购买 nike

<分区>

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

现在,如果字符串位于运算符的右侧,它就可以工作。但是如何重载 == 以便它在字符串位于运算符左侧时也能正常工作。

这里是 link ideone 中的代码。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com