如何创建要在std :: ostream或std :: cout中使用的函数

问题描述 投票:0回答:2

是否有一种方法可以创建可在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 USD

我更喜欢不需要类的解决方案。如果必须使用一个类,则在使用usd函数时,我根本不愿提及该类。 (例如std::setw功能的工作方式)

编辑:在我的实现中,我打算使用std::hex函数,上述函数只是一个简化的示例,但可能不应该使用。

std::ostream& hex(std::ostream& os, int value) {
    os << "Hex: " << std::hex << value;
    return os;
}

所以我不确定返回简单字符串的函数是否足够。

c++ iostream
2个回答
3
投票

要获得您描述的用法:

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";
}

您可以编写其他功能以其他货币打印,或在其他货币之间进行转换,等等,但是如果您要处理的只是美元,这就足够了。


[如果您使用的是代表金钱的类,则可以为该类编写一个ostream<<,并且根本不需要调用函数(假设您的默认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;
}

0
投票

我不上课就不知道该怎么做。但是,使用类很容易。

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.