我正在尝试用 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;
}
最佳答案
这一行
std::cout << hexa << value << std::endl;
写入一个指针(指向函数 hexa)。应该调用该函数。
关于用于十六进制整数的 C++ 自定义 I/O 操纵器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35945417/