[英]Where to put helper functions pertaining to class method in C++
Suppose I have a class Foo
like this:假设我有一个这样的类
Foo
:
foo.h : foo.h :
namespace mine {
class Foo {
Widget widget_;
public:
void bar();
// some other members...
};
} // namespace mine
foo.cpp : foo.cpp :
#include "foo.h"
namespace mine {
void Foo::bar() {
// Some very long code
}
} // namespace mine
where I want to split bar()
into multiple functions for readability reasons.出于可读性原因,我想将
bar()
拆分为多个函数。 The functions themselves don't have any particular meaning to Foo
(or any other entity than Foo::bar()
) and are only used to split up bar()
, so according to this discussion I would do the following in the source file:函数本身对
Foo
(或除Foo::bar()
之外的任何其他实体)没有任何特殊意义,仅用于拆分bar()
,因此根据此讨论,我将在源文件中执行以下操作:
foo.cpp (refactored): foo.cpp (重构):
#include "foo.h"
// anonymous namespace to put all helper functions
namespace {
void computeResult() { ... }
void modifyWidget(Widget& w) { ... }
void doThis() { ... }
void doThat(Widget& w) {
// ...
modifyWidget(w);
}
} // <anonymous> namespace
// actual methods are defined here
namespace mine {
void Foo::bar() {
::doThis();
::doThat(widget_);
::computeResult();
}
} // namespace mine
So I am defining an anonymous namespace in the source file in order to define the helper functions, such that I have static linkage and the helper functions are not visible from outside the source file.所以我在源文件中定义了一个匿名命名空间,以便定义辅助函数,这样我就有了静态链接,辅助函数在源文件外部是不可见的。 One thing that looks odd to me is that class methods depend on functions that are not part of the class, but then we would not be able to use even the standard library if this was an issue.
对我来说看起来很奇怪的一件事是类方法依赖于不属于类的函数,但是如果这是一个问题,我们甚至无法使用标准库。
Foo::widget_
to some freestanding function that modifies it ( doThat()
)?Foo::widget_
给一些修改它的独立函数( doThat()
)是否有问题? I'm assuming here that in the narrow context of a static linkage helper function, the callers/callees know what they are doing.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.