• 【 c++ 二元运算符重载,以<<(抽取符)为例,说清为什么它支持hex,endl等操作函数】


    /* author: hjjdebug
       date  : 2023年 09月 24日 星期日 16:29:55 CST
       description: c++ 的 cout 对象, 及hex,endl,showbase等控制函数很难说清其工作原理
       网上的文章也都在讲它怎么用,但没有讲为什么这么用,及为什么它能这么用!,
       这里干脆用c 代码的形式实现一次, 就知道它们的工作原理了.
       是的,这得益于c++ 对操作符的重载!
         c++ 二元运算符重载,以<<(抽取符)为例,说清为什么它支持hex,endl等操作函数

       */
    #include

    class my_ostream
    {
    public:
        my_ostream &operator<<(int d);
        my_ostream &operator<<( my_ostream& fun(my_ostream &));
        friend     my_ostream &hex(my_ostream &os);
        friend     my_ostream &dec(my_ostream &os);
        
    private:
        int m_type=0;
    };
    // 重载 << 操作符
    // 返回值 是this 对象
    // 根据this 对象的属性,给出不同的类型输出
    my_ostream &my_ostream::operator<<(int d)
    {

        if(m_type==0)
        {
            printf("%d\n",d);
            
        }
        else if(m_type==1)
        {
            printf("0x%x\n",d);
        }
        return *this;
    }


    //也可以定义一个函数类型简化书写,typedef my_ostream& HEX(my_ostream &);
    //要想支持hex函数,需定义一个hex那样的函数类型为它的参数, 继续重载<< 操作符
    //执行这个函数,把this对象传给这个函数做参数,从而改变this 对象的属性

    my_ostream &my_ostream::operator<<(my_ostream& fun( my_ostream &))
    {
        fun(*this); //执行这个函数,把this对象传给这个函数做参数
        return *this;
    }

    //定义hex 函数, 可以修改os 的一些属性
    my_ostream &hex( my_ostream &os)
    {
        os.m_type=1;
        return os;
    }
    my_ostream &dec( my_ostream &os)
    {
        os.m_type=0;
        return os;
    }

    int main()
    {
        my_ostream my_cout;
        my_cout<<100;
        my_cout<     return 0;
    }

    /* 执行结果
       ./test
       100
       0x64
       100
    */

  • 相关阅读:
    dos2unix命令
    Spring Cloud 架构设计之linux yum redis
    VMwareworkstation安装Centos7教程
    码农跃迁三角色:程序员、技术主管与架构师
    NoClassDefFoundError: org/tukaani/xz/FilterOptions
    基于银河麒麟V10SP1的git使用方法-上传篇
    Ni-IDA琼脂糖凝胶FF-------可用于纯化带组氨酸标签(His-Tag)的重组蛋白
    Python 中并发方面的差异
    北京冬奥一项AI黑科技即将走进大众:实时动捕三维姿态,误差不到5毫米
    【shell】$# 获取函数参数
  • 原文地址:https://blog.csdn.net/hejinjing_tom_com/article/details/133244295