运算符重载:成员函数与非成员函数?

Operator overloading : member function vs. non-member function?(运算符重载:成员函数与非成员函数?)

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

问题描述

我读到声明为成员函数的重载运算符是非对称,因为它只能有一个参数,而另一个自动传递的参数是 this 指针.所以不存在比较它们的标准.另一方面,声明为 friend 的重载运算符是对称,因为我们传递了两个相同类型的参数,因此它们可以进行比较.

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.

我的问题是,当我仍然可以将指针的左值与引用进行比较时,为什么首选朋友?(使用非对称版本的结果与对称版本相同)为什么 STL 算法只使用对称版本?

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.运算符+(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.

为了解决这个排序问题,我们将运算符重载函数定义为friend,如果它需要访问private成员.仅在需要访问私人成员时才将其设为好友.否则只需将其设为非好友非会员功能即可改进 封装!

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
}

阅读这些:
一个小问题操作数
非成员函数如何改进封装

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

本文标题为:运算符重载:成员函数与非成员函数?

基础教程推荐