[英]Pass std::istream and std::ostream by reference to be used from within function
[英]How to create a function to be used in an std::ostream or std::cout
有沒有辦法創建一個 function 可以在 ostream 中的兩個<<
運算符之間使用?
假設函數的名稱是usd
,可能看起來像:
std::ostream& usd(std::ostream& os, int value) {
os << "$" << value << " USD";
return os;
}
然后我想像這樣使用它:
int a = 5;
std::cout << "You have: " << usd(a) << std::endl;
哪個會打印:
你有:5 美元
我更喜歡不需要 class 的解決方案。 如果您必須使用 class,我寧願在使用usd
function 時根本不提及 class。 (例如std::setw
function 如何工作)
編輯:
在我的實現中,我打算使用std::hex
function,上面描述的只是一個簡化的例子,但可能不應該有。
std::ostream& hex(std::ostream& os, int value) {
os << "Hex: " << std::hex << value;
return os;
}
所以我不確定返回簡單字符串的 function 是否足夠。
要獲得您描述的用法:
int a = 5;
std::cout << "You have: " << usd(a) << std::endl;
您只需要usd(a)
來返回您擁有ostream<<
運算符的東西,例如std::string
,並且不需要自定義ostream<<
運算符。
例如:
std::string usd(int amount)
{
return "$" + std::to_string(amount) + " USD";
}
您可以編寫其他函數以其他貨幣打印,或在它們之間進行轉換等,但如果您只想處理美元,這就足夠了。
如果您使用代表貨幣的 class,您可以為該 class 編寫ostream<<
並且您根本不需要調用 function (假設您的默認值打印 USD ostream<<
)
class Money
{
int amount;
};
std::ostream& usd(std::ostream& os, Money value) {
os << "$" << value.amount << " USD";
return os;
}
int main(int argc, char** argv)
{
Money a{5};
std::cout << "You have: " << a << std::endl; // Prints "You have: $5 USD"
return 0;
}
如果沒有 class,我不知道該怎么做。 但是,使用 class 很容易做到。
struct usd {
int value;
constexpr usd(int val) noexcept : value(val) {}
};
std::ostream& operator<<(std::ostream& os, usd value) {
os << "$" << value.value << " USD";
return os;
}
十六進制
struct hex {
int value;
constexpr hex(int val) noexcept : value(val) {}
};
std::ostream& operator<<(std::ostream& os, hex value) {
os << "Hex: " << std::hex << value.value;
return os;
}
用法
int a = 5;
std::cout << "You have: " << usd(a) << std::endl;
std::cout << "You have: " << hex(a) << std::endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.