在编写自己的流运算符时,如何检查当前的 ostream dec/hex 模式?

How can I check the current ostream dec/hex mode when writing my own streaming operator?

本文关键字:ostream dec 模式 hex 检查 自己的 运算符 何检查      更新时间:2023-10-16

我正在编写一个简单的类,它有一个朋友来写入输出流,例如std::cout

我的类的状态可以用数字形式表示,我可能希望看到十进制或十六进制。

如果我正在打印一个 PODint,我可以使用std::hex修饰符;我想做的是在我的函数中检查它并采取相应的行动。 到目前为止,我的搜索是空白的。

class Example
{
friend std::ostream& operator<<( std::ostream& o, const Example& e );
};
std::ostream& operator<<( std::ostream& o, const Example& e )
{
if ( /*check for hex mode*/ )
o << "hexadecimal";
else
o << "decimal";
return o;
}

我应该用什么来代替/*check for hex mode*/

编辑:我使我的例子超级通用。

您可以使用ostreamflags()函数,查看是否设置了hex位:

bool isHexMode(std::ostream& os) {
return (os.flags() & std::ios_base::hex) != 0;
}

回答我自己的问题,感谢@AProgrammer为我指出正确的方向。

std::ostream& operator<<( std::ostream& o, const Example& e )
{
if ( o.flags() & std::ios_base::hex )  // <-----
o << "hexadecimal";
else
o << "not hexadecimal";
return o;
}