【发布时间】:2016-03-11 16:37:31
【问题描述】:
我正在尝试用 C++ 编写一个自定义 I/O 操纵器,它可以根据提供的大小以0xFFFF 的形式编写格式良好的十六进制整数。
例如:
-
char c = 1变为0x01 -
short s = 1变为0x0001
等等。 在我的代码中找不到错误,即打印垃圾:
#include <iostream>
#include <iomanip>
class hexa_s
{
mutable std::ostream *_out;
template<typename T>
const hexa_s& operator << (const T & data) const
{
*_out << std::internal << std::setfill( '0' ) << std::hex << std::showbase << std::setw( sizeof( T ) * 2 ) << data;
return *this;
}
friend const hexa_s& operator <<( std::ostream& out, const hexa_s& b )
{
b._out = &out;
return b;
}
};
hexa_s hexa( )
{
return hexa_s( );
}
int main()
{
int value = 4;
std::cout << hexa << value << std::endl;
return 0;
}
【问题讨论】:
-
它应该是
sizeof(T) * CHAR_BIT / 4,或者更好的是std::numeric_limits<T>::digits() / 4(也许有适当的四舍五入)。