如何重载 == 运算符而不使其成为友元函数?

Tra*_*net 1 c++ class operator-overloading friend c++17

我有一个类SomeClass,我希望实现一个重载==来比较这个类的两个实例。

重载==不使用任何SomeClass私有成员。因此,它不必是friend.

我如何使它成为非会员、非好友功能?

目前,这就是我的代码的样子:

某个类.h

#ifndef SOMECLASS_H
#define SOMECLASS_H

class SomeClass
{
public:
    // Other class declarations, constructors
    friend bool operator==(const SomeClass a, const SomeClass b);
};
Run Code Online (Sandbox Code Playgroud)

某个类.cpp

#include "someclass.h"

// Other stuff 

bool operator==(const SomeClass a, const SomeClass b) {
// do some comparison and return true/false
}
Run Code Online (Sandbox Code Playgroud)

JeJ*_*eJo 5

Like @HolyBlackCat pointed out, you can provide the operator== overload as a free function. It will be a free-function, meaning you can either write

#ifndef SOMECLASS_H
#define SOMECLASS_H

// namespaces if any

class SomeClass
{
    // Other class declarations, constructors
};

bool operator==(const SomeClass& a, const SomeClass& b) noexcept
{
    // definition
}

// end of namespaces if any!

#endif  // end of SOMECLASS_H
Run Code Online (Sandbox Code Playgroud)

or

declare operator== in the header and provide the definition of the free function in the corresponding cpp file

  • 如果您在标头中声明并定义该运算符,则最好将其声明为内联。否则,如果您碰巧将该标头包含在多个编译单元中,链接器将发出警告。 (4认同)