操作员覆盖 - 什么时候使用朋友? [英] Operator override - when to use friend?

查看:90
本文介绍了操作员覆盖 - 什么时候使用朋友?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么()操作符重写不能是朋友(因此它需要一个这附加参数),而+操作符需要是朋友,如下面的例子:

I'm wondering why the () operator override can't be "friend" (and so it needs a "this" additional parameter) while the + operator needs to be friend like in the following example:

class fnobj
{
    int operator()(int i);
    friend int operator+(fnobj& e);
};

int fnobj::operator()(int i)
{

}

int operator+(fnobj& e)
{

}

我理解+操作符需要朋友避免额外额外的参数,但是为什么操作符()不需要它?

I understood that the + operator needs to be friend to avoid the "additional" extra this parameter, but why is that the operator() doesn't need it?

推荐答案

您已重载一元加运算符。你可能不想这样做。它不添加两个对象,它描述如何在 + 出现之前解释单个对象,与 int x = +10 将被解释。 (与 int x = 10 相同)

You have overloaded the unary plus operator. And you probably didn't want to do that. It does not add two objects, it describes how to interpret a single object when a + appears before it, the same as int x = +10 would be interpreted. (It's interpreted the same as int x = 10)

对于加法运算符 ,+操作员需要是朋友是不正确的。

For the addition operator, it is not correct that "the + operator needs to be friend".

以下是添加两个 fnobj 对象的两种方法:

Here are two ways to add two fnobj objects:

int operator+(fnobj& e);
friend int operator+(fnobj& left, fnobj& right);

在第一种形式中,假设 this 成为 + 左侧的对象。因此,两种形式都有两个参数。

In the first form, this is presumed to be the object to the left of the +. So both forms effectively take two parameters.

因此,为了回答你的问题,而不是认为operator c $ c> friend ,认为它是operator()requires this 或者更好的是,对象。

So to answer your question, instead of thinking that "operator() doesn't need friend", consider it as "operator() requires this" Or better still, "Treating an object as a function requires an object".

这篇关于操作员覆盖 - 什么时候使用朋友?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆