![](/img/trans.png)
[英]Should helper functions be excluded from header file declarations? (C++)
[英]How to go about hiding "helper functions" from the interface of a header file
我正在嘗試實現一個 Money 類,該類具有貨幣表示(如 $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 類(稍后我將添加一些更有用的操作),因此他們沒有任何理由調用to_cents。
我擔心的是,如果我在cpp文件中聲明它,而用戶在單獨的文件中創建另一個同名的函數,則會出現名稱沖突,從而導致鏈接器錯誤。 但是除了把它作為Money 的私有成員之外,我想不出任何其他方法可以將to_cents 從界面中隱藏起來。 使它成為 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) {
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.