操作符重载:成员函数与非成员函数? [英] Operator overloading : member function vs. non-member function?

查看:144
本文介绍了操作符重载:成员函数与非成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到一个重载的运算符声明为成员函数是不对称的,因为它只能有一个参数,而自动传递的另一个参数是'this'指针。因此,没有标准可以比较。另一方面,声明为朋友的重载运算符是对称的,因为我们传递两个相同类型的参数,因此,它们可以被比较。
我的问题是,当我仍然可以比较指针的左值和引用,为什么是朋友首选? (使用不对称版本给出与对称相同的结果)
为什么STL算法只使用对称版本?

I read that an overloaded operator declared as member function is asymmetric because it can have only one parameter and the other parameter passed automatically is the 'this' pointer. So no standard exists to compare them. On the other hand, overloaded operator declared as a friend is symmetric because we pass two arguments of the same type and hence, they can be compared. My question is that when i can still compare a pointer's lvalue to a reference, why are friends preferred? (using an asymmetric version gives the same results as symmetric) Why do STL algorithms use only symmetric versions?

推荐答案

如果将运算符重载函数定义为成员函数,则编译器将 s1 + s2 的表达式转换为 s1.operator +(s2)这意味着,操作符重载的成员函数在第一个操作数上被调用。这是成员函数的工作原理!

If you define your operator overloaded function as member function, then the compiler translates expressions like s1 + s2 into s1.operator+(s2). That means, the operator overloaded member function gets invoked on the first operand. That is how member functions work!

但是如果第一个操作数不是一个类? 如果我们想重载一个运算符,其中第一个操作数不是类类型,而是 double 10.0 + s2 。但是,您可以为 s1 + 10.0 的表达式编写运算符重载的成员函数。

But what if the first operand is not a class? There's a major problem if we want to overload an operator where the first operand is not a class type, rather say double. So you cannot write like this 10.0 + s2. However, you can write operator overloaded member function for expressions like s1 + 10.0.

如果它需要访问 private 成员,我们定义运算符重载函数为 friend 仅在需要访问私人会员时才设置 c 。改进封装!

To solve this ordering problem, we define operator overloaded function as friend IF it needs to access private members. Make it friend ONLY when it needs to access private members. Otherwise simply make it non-friend non-member function to improve encapsulation!

class Sample
{
 public:
    Sample operator + (const Sample& op2); //works with s1 + s2
    Sample operator + (double op2); //works with s1 + 10.0

   //Make it `friend` only when it needs to access private members. 
   //Otherwise simply make it **non-friend non-member** function.
    friend Sample operator + (double op1, const Sample& op2); //works with 10.0 + s2
}

阅读这些内容:

操作数中的排序略有问题

非会员功能如何改善封装

这篇关于操作符重载:成员函数与非成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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