操纵器、应用器

来源:互联网 发布:阿里云网站搭建 编辑:程序博客网 时间:2024/03/29 10:16

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;}
原创粉丝点击