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
}
阅读这些:
一个小问题操作数
非成员函数如何改进封装
这篇关于运算符重载:成员函数与非成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:运算符重载:成员函数与非成员函数?
基础教程推荐
- 设计字符串本地化的最佳方法 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01