简体   繁体   English

在C ++中重写运算符的首选方法是什么

[英]What is the preferred way to override operators in C++

I was always overriding operators like this: 我总是像这样覆盖运算符:

class MyClass {
public:
    ...
    MyClass operator+(const MyClass&) const;

private:
    int some_number = 5;
}

MyClass MyClass::operator+(const MyClass& rhs) const
{
    return MyClass(some_number + rhs.some_number);
}

But today I realized you can create operators with the 'friend' keyword too: 但是今天我意识到您也可以使用'friend'关键字创建运算符:

class MyClass {
public:
...
friend MyClass operator+(const MyClass&, const MyClass&);

private:
    int some_number = 5;
} 

MyClass operator+(const MyClass& lhs, const Myclass& rhs)
{
    return MyClass(lhs.some_number + rhs.some_number);
}

Which would be the preferred way considering I want left-sided and right-sided operators and I also (try to) follow the Core Guidelines? 考虑到我想要左侧和右侧运算符并且我也(尝试)遵循“核心准则”,哪种方法是首选?

The preferred way is to not even make it a friend: 首选的方法是甚至不让它成为朋友:

MyClass operator+(MyClass lhs, Myclass const& rhs)
{
    return lhs += rhs;
}

Of course, this does rely on operator+= but that is the more fundamental operation. 当然,这确实依赖于operator+=但这是更基本的操作。 += alters its left-hand side and should be a member. +=更改其左侧,应为成员。

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

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