c++ primer plus提到,hex是一个函数,hex(cout)效果和cout<<hex一样,将使后面的输入全部变成16进制。本身用法都知道,唯一奇怪的是这个hex为什么能被重载。
比如operator<<(int ){....},那么起码后面要接一个int类型,但是hex是函数名,为何可以重载?
经过反复测试,其实hex被计算机理解为了函数指针类型。于是我伪造了一个IOS类,并构造了一个Cout对象,Cout<<Hex,就是重载了函数指针类型的变量,使他等同于Hex(Cout)
经过Cout<<Hex后,,后面的输出变为五进制。
代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
void Hex(class IOS& a);
class IOS
{
int i,a[10];
static int k;
public:
IOS() {i=0;}//默认构造函数
void operator<<(void (*f)(class IOS& a) ) {f(*this);}//重载 void (*)(class Cout& a类型的函数指针
void operator<<(int c); //重载int类型的<<
friend void Hex(class IOS& a);//友元函数,与上面 f(*this)对应 ,把输入的数字以五进制输出
};
int IOS::k=0;
int main()
{
IOS Cout;
Cout<<55;
cout<<"\n使用了Cout<<Hex之后(输出变为五进制):\n";
Cout<<Hex;//用法类似cout<<hex
Cout<<55;
getchar ();
return 0;
}
void Hex(class IOS& a) {IOS::k=1;}//输出选择改变
void IOS::operator<<(int c)
{
if (k==0) cout<<c;
else
{
while (c) {a[i++]=c%5;c/=5;}
while (i!=0) cout<<a[--i];
}
}
效果: