C++ Member Functions vs Free Functions(C++ 成员函数与自由函数)
问题描述
在编写程序时,很多时候我一直对这个设计决定感到困惑,但我不能 100% 确定何时应该使函数成为类的成员函数,何时离开它作为一个普通函数,当函数声明在头文件中公开时,其他源文件可以调用该函数.大多数情况下,对类成员变量的期望访问是否与决策有关?
界面原理 by Herb Sutter
对于类 X,所有函数,包括自由函数,都
(a) 提及"X,和
(b) 随附" X
逻辑上是 X 的一部分,因为它们构成 X 接口的一部分.
有关深入讨论,请阅读 Herb Sutter 的命名空间和接口原则.>
编辑
实际上,如果您想了解 C++,请阅读所有内容 Herb Sutter 写的内容:)
I keep on getting confused about this design decision a lot of the time when I'm writing programs, but I'm not 100% sure when I should make a function to be a member function of a class, when to leave it as a normal function in which other source files can call the function when the function declaration is exposed in a header file. Does the desired access to member variables of a class have to do with the decision most of the time?
The Interface Principle by Herb Sutter
For a class X, all functions, including free functions, that both
(a) "mention" X, and
(b) are "supplied with" X
are logically part of X, because they form part of the interface of X.
For in depth discussion read Namespaces and the Interface Principle by Herb Sutter.
EDIT
Actually, if you want to understand C++ go and read everything what Herb Sutter has written :)
这篇关于C++ 成员函数与自由函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 成员函数与自由函数
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
