C++运算符==重载

mfc*_*mfc 11 c++ operator-overloading

可能重复:
运算符重载

以下重载operator ==的方法有什么区别?

// stroustrup way
friend bool operator== (MyClass &lhs, MyClass &rhs); 
Run Code Online (Sandbox Code Playgroud)

// as taught in other places, including caltech
bool MyClass::operator== (MyClass &rhs);
Run Code Online (Sandbox Code Playgroud)

哪种方式更好?

BЈо*_*вић 6

这 :

friend bool operator== (MyClass &lhs, MyClass &rhs); 
Run Code Online (Sandbox Code Playgroud)

是一个函数,用于比较两个对象。

这 :

bool MyClass::operator== (MyClass &rhs);
Run Code Online (Sandbox Code Playgroud)

是一个成员函数。

您应该使用您的编码标准建议的一种,或者使用您喜欢的一种。没有一个更好。有些人(包括我自己)更喜欢将比较运算符作为函数,其他人更喜欢将其作为成员函数。

顺便说一下,参数应该是const MyClass &类型的。


小智 6

首先是外部好友功能(免费功能)

friend bool operator== (MyClass &lhs, MyClass &rhs); 
Run Code Online (Sandbox Code Playgroud)

二是成员函数

bool MyClass::operator== (MyClass &rhs);
Run Code Online (Sandbox Code Playgroud)

你应该总是使用第二个变体然后你可以

您应该在以下情况下使用第一个变体:1)第一个参数是外部(库)类

friend ostream& operator<< (ostream &out, MyClass &m)
Run Code Online (Sandbox Code Playgroud)

2) Operator 的逻辑与你的类无关,必须单独实现

friend bool operator(const MyClass& my, const std::string& string_form)
Run Code Online (Sandbox Code Playgroud)

(因为您的班级无法了解比较运算符中可能需要的所有类)


Ton*_*roy 5

// stroustrup way
friend bool operator== (MyClass &lhs, MyClass &rhs);
Run Code Online (Sandbox Code Playgroud)

参数应为const

friend bool operator==(const MyClass& lhs, const MyClass& rhs);
Run Code Online (Sandbox Code Playgroud)

这是首选方法,因为它可以在第一个参数可以隐式构造时使用。例如,如果std::string仅具有一个成员函数operator==,则"abc" == my_std_string不会调用它!但是,可以通过从“ abc”隐式构造一个字符串来调用非成员函数(更好的是,在这种情况下,bool operator==(const char*, const std::string&)出于性能原因可以提供一个单独的字符串,但要点仍然存在-非成员函数可以帮助确保运算符可与任一侧的用户定义类型一起使用)。

另外,隐式构造函数有点危险-您需要认真考虑使用它们的便利性和危险性。

最后一点:如果没有其他方法可以访问需要比较的数据,则只需将非成员设置为operator==a friend。否则,您可以在类外部声明/定义它,如果希望将实现包含在最终可能链接到同一可执行文件的多个翻译单元中,则可以选择内联。不过危害不大,并且让它成为朋友是将定义放入类模板的唯一方法,而不必重复“模板”的内容和参数。