C ++操作符覆盖 - 为什么它是朋友首选? [英] C++ operator override - why is it friend preferred?

查看:176
本文介绍了C ++操作符覆盖 - 为什么它是朋友首选?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继续上一个问题,我想要要求总结:

Continuing from the previous question I'd like to ask why the "friend" form of addition in a C++ operator override is preferred

对于加法操作符覆盖有两种方法来实现它:

for the addition operator override there are two ways to do it:

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

为什么第二个(朋友)有什么优点?

why is that the second (friend) form is preferred? What are the advantages?

推荐答案

非成员版本(朋友或其他)是首选,因为它可以支持

The non-member version (friend or otherwise) is preferred because it can support implicit conversions on both the left and right side of the operator.

给定一个可隐式转换为Object的类型:

Given a type that is implicitly convertible to Object:

struct Widget
{
  operator Object() const;
};

只有非成员版本才能被调用,如果 Widget 出现在左侧:

Only the non-member version can be called if an instance of Widget appears on the left-hand side:

Widget w;
Object o;

o + w; // can call Object::operator+( Object & ) since left-hand side is Object
w + o; // can only call operator+( Object &, Object & )






响应您的评论:


In response to your comment:

通过在 Widget 中定义转换运算符,编译器 Widget 的实例可以自动转换为 Object 的实例。

By defining the conversion operator in Widget, we are notifying the compiler that instances of Widget can be automatically converted to instances of Object.

Widget w;
Object o = w;  // conversion

在表达式 o + w ,编译器调用 Object :: operator +(Object&),其参数通过将 w code> Object 。所以结果与写 o + w.operator Object()相同。

In the expression o + w, the compiler calls Object::operator+( Object & ) with an argument generated by converting w to an Object. So the result is the same as writing o + w.operator Object().

但是在表达式 w + o ,编译器会查找 Widget :: operator + (不存在) code> operator +(Widget,Object)。后者可以通过将 w 转换为如上所述的对象来调用。

But in the expression w + o, the compiler looks for Widget::operator+ (which doesn't exist) or a non-member operator+( Widget, Object ). The latter can be called by converting w to an Object as above.

这篇关于C ++操作符覆盖 - 为什么它是朋友首选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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