操纵器、应用器

c++有许多输出操纵符,例如ostream& flush(ostream&o)
它却可以使用cout<<flush,这是如何做到的呢?

#include <iostream>
using namespace std;


char* to_hex(unsigned long x){
    static char ret[20] = "0x0\0";
    static char table[17]="0123456789ABCDE";
    int i = 2;
    if (x == 0){ return "0x0\0"; }
    while(x!=0){
        ret[i++] = table[x%16];
        x /= 16;
    }
    ret[i--] = '\0';
    int j = 2;
    while(j<i){
        ret[i] ^= ret[j];
        ret[j] ^= ret[i];
        ret[i] ^= ret[j];
        ++j;--i;
    }
    return ret;
}

class To_Hex{
public:
    To_Hex(char* (* tohex)(unsigned long),unsigned long x) :m_tohex(tohex),m_x(x){}
    void operator()(ostream& o)const{
        o << (*m_tohex)(m_x);
    }
private:
    char* (* m_tohex)(unsigned long);
    unsigned long m_x;
};

ostream& operator<<(ostream& o, const To_Hex& to){
    to(o); 
    return o;
}

To_Hex hexconv(unsigned long x){
    return To_Hex(to_hex,x);
}

int main(){
    cout << to_hex(0) << ends << to_hex(16) << ends << to_hex(10) << endl;
    //hexconv()->   const To_Hex->  operator<<()->  operator()->    to_hex()
    cout << hexconv(0) << ends << hexconv(16) << ends << hexconv(10) << endl;
    cout << hexconv(0) << ends << hexconv(16) << ends << hexconv(10) << endl;
    cout << hexconv(0) << ends << hexconv(16) << ends << hexconv(10) << endl;
    cout << hexconv(0) << ends << hexconv(16) << ends << hexconv(10) << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值