我希望能够为我的类重载==
运算符,以便我可以将我的类的属性与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上代码的链接。
text(std::move(msg))
。 - M.M