简体   繁体   English

如何重载 == 运算符而不使其成为朋友 function?

[英]How to overload == operator without making it a friend function?

I have a class SomeClass and I wish to implement an overloaded == to compare two instances of this class.我有一个 class SomeClass ,我希望实现一个重载==来比较这个 class 的两个实例。

The overloaded == does not make use of any of SomeClass 's private members.重载的==不使用SomeClass的任何私有成员。 So, it does not have to be a friend .所以,它不一定是friend

How do I make it a non-member, non-friend function?如何使其成为非会员、非朋友 function?

Currently, this is what my code looks like:目前,这是我的代码的样子:

someclass.h某个类.h

#ifndef SOMECLASS_H
#define SOMECLASS_H

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

someclass.cpp某类.cpp

#include "someclass.h"

// Other stuff 

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

Like @HolyBlackCat pointed out, you can provide the operator== overload as a free function.就像@HolyBlackCat指出的那样,您可以提供operator==重载作为免费的 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

or或者

declare operator== in the header and provide the definition of the free function in the corresponding cpp file在 header 中声明operator==并在对应的 cpp 文件中提供免费 function 的定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM