尽可能避免使用宏!它们隐藏代码,使得调试变得困难,不尊重作用域等。您可以像KenE提供的那样使用简单的函数。如果您想变得花哨和灵活,那么可以编写自己的操纵器:
#include <iostream>
#include <iomanip>
using namespace std;
ostream& hex4(ostream& out)
{
return out << "0x" << hex << setw(4) << setfill('0');
}
int main()
{
cout << hex4 << 123 << endl;
}
这使得它更加通用。以上函数能够使用的原因是因为operator<<
已经像这样被重载:ostream& operator<<(ostream&, ostream& (*funtion_ptr)(ostream&))
。例如,endl
和其他一些操纵符也是这样实现的。
如果您想在运行时允许指定小数位数,我们可以使用一个类:
#include <iostream>
#include <iomanip>
using namespace std;
struct formatted_hex
{
unsigned int n;
explicit formatted_hex(unsigned int in): n(in) {}
};
ostream& operator<<(ostream& out, const formatted_hex& fh)
{
return out << "0x" << hex << setw(fh.n) << setfill('0');
}
int main()
{
cout << formatted_hex(4) << 123 << endl;
}
然而,如果大小可以在编译时确定,最好使用函数模板[感谢Jon Purdy提供的建议]:
template <unsigned int N>
ostream& formatted_hex(ostream& out)
{
return out << "0x" << hex << setw(N) << setfill('0');
}
int main()
{
cout << formatted_hex<4> << 123 << endl;
}