重载操作符作为成员函数还是非成员(朋友)函数? [英] Overload operators as member function or non-member (friend) function?

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

问题描述

我目前正在创建一个实用程序类,它将有重载的运算符。将它们成为成员或非成员( friend )的功能有什么利弊?还是有什么关系?

解决方案

每个操作符都有自己的注意事项。例如,<<运算符(当用于流输出,而不是位移位)获取一个ostream作为它的第一个参数,所以它不能是你的类的成员。如果您正在实施加法运算符,您可能希望从双方的自动类型转换中获益,因此您将与非会员一起使用等。


$对于允许通过继承进行专门化,通常的模式是根据虚拟成员函数(例如,操作符<调用正在传递的对象上的虚拟函数print())来实现非成员运算符, 。


I am currently creating a utility class that will have overloaded operators in it. What are the pros and cons of either making them member or non-member (friend) functions? Or does it matter at all? Maybe there is a best practice for this?

解决方案

Each operator has its own considerations. For example, the << operator (when used for stream output, not bit shifting) gets an ostream as its first parameter, so it can't be a member of your class. If you're implementing the addition operator, you'll probably want to benefit from automatic type conversions on both sides, therefore you'll go with a non-member as well, etc...

As for allowing specialization through inheritance, a common pattern is to implement a non-member operator in terms of a virtual member function (e.g. operator<< calls a virtual function print() on the object being passed).

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

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