如何从头文件的接口中隐藏 "helper functions"

How to go about hiding "helper functions" from the interface of a header file

我正在尝试实现一个货币 class,它具有货币表示(如 $13.00、$18.92 等)和一组操作。到目前为止,这是头文件:

#include <iostream>

namespace Currency {

class Money {
private:
    long int total_cents = 0;
public:
    Money();
    Money(long int c);
    Money(long int d, int c);
    long int get_cents() const {return total_cents;}
    //Money(float dollars); // TODO
};

std::ostream& operator<<(std::ostream& os, const Money& m);
std::istream& operator>>(std::istream& is, const Money& m);

// Returns the total number of cents in $d.c
long int to_cents(long int d, int c);


}

我的问题是我不打算将最后一个辅助函数作为接口的一部分,所以我只想在 cpp 文件中将它定义为一个实现函数。我只希望构造函数 Money(long int, int) 调用它,而用户只会处理 Money class (我稍后会添加一些更有用的操作),所以他们不会有任何理由打电话 to_cents。

我担心的是,如果我在cpp文件中声明,而用户在单独的文件中创建另一个同名函数,就会出现名称冲突,从而导致链接器错误。但我想不出任何其他方法来从界面中隐藏 to_cents,除了将其作为 Money 的私有成员。使它成为 Money 的私有成员没有多大意义,因为它不读取或写入其任何数据成员。另一种选择是在构造函数中写出函数,但我认为它作为逻辑上独立的计算,因此它应该是它自己的函数。从这里出发的最佳方式是什么?

如果有什么需要详细说明的,请告诉我,谢谢!

您可以通过将函数包装在匿名命名空间中来定义源文件的本地函数:

// in your cpp file:
namespace {
  long to_cents(long d, int c) {
    // ...
  }
}

您也可以通过将其设为 static 函数来做同样的事情:

// in your cpp file
static long to_cents(long d, int c) {
  // ...
}