将函数实现为自由函数而不是C ++中的成员有什么好处? [英] Is there any advantage to implementing functions as free functions rather than members in C++?

查看:66
本文介绍了将函数实现为自由函数而不是C ++中的成员有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对技术物流很感兴趣.实现某些处理类的功能是否有任何优势(例如节省内存等)?

I'm interested in the technical logistics. Is there any advantage, such as memory saved, etc., to implementing certain functions dealing with a class?

特别是,将运算符重载实现为自由函数(前提是您不需要访问任何私有成员,即使这样,您也可以使他们使用非成员的朋友)?

In particular, implementing operator overloads as free functions (providing you don't need access to any private members, and even then you can make them use a friend non-member)?

每次创建对象时,是否为该类的每个功能提供了不同的内存地址?

Is a distinct memory address provided for each function of the class each time an object is created?

推荐答案

此答案可能会帮助您:

This answer may helps you : Operator overloading : member function vs. non-member function?. In general free functions is mandatory if you need to implement operators on classes you don't have access to code source (think about streams) or if left operand is not of class type (int for example). If you control the code of the class then you can freely use function members.

对于最后一个问题,不,函数成员是唯一定义的,并且使用对象内部表指向它们.可以将函数成员视为具有隐藏参数(指向对象的指针)的自由函数, ie o.f(a)f(&o,a)大致相同,而原型大致类似于f(C *this,A a);.

For your last question, no, function members are uniquely defined and an object internal table is used to point to them. Function members can be viewed as free functions with an hidden parameter that is a pointer to the object, i.e. o.f(a) is more or less the same as f(&o,a) with a prototype roughly like f(C *this,A a);.

这篇关于将函数实现为自由函数而不是C ++中的成员有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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