简体   繁体   English

在 C++ 中放置与类方法有关的辅助函数的位置

[英]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.对我来说看起来很奇怪的一件事是类方法依赖于不属于类的函数,但是如果这是一个问题,我们甚至无法使用标准库。

  • Is this approach sensible?这种方法是否明智? Do you have better suggestions?你有更好的建议吗?
  • Is there a problem with passing the private member 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.我在这里假设在静态链接辅助函数的狭窄上下文中,调用者/被调用者知道他们在做什么。
  1. Yes, it's sensible.是的,这是明智的。 It's also not uncommon, and it's my impression that it's gaining popularity.这也并不少见,我的印象是它越来越受欢迎。
  2. Linkage has no effect whatsoever on how functions work, and a private member variable works exactly like all other variables (except you can't access its name from the outside).链接对函数的工作方式没有任何影响,私有成员变量的工作方式与所有其他变量完全一样(除非您无法从外部访问其名称)。
    That is, it's exactly like passing any variable to any function.也就是说,它就像将任何变量传递给任何函数一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM