zoukankan      html  css  js  c++  java
  • C++中对封装的语法支持——this指针

    this指针

    1、this概念

    (1) This指针就是用于成员函数区分调用对象。

    (2) This指针由编译器自动传递,无须手动传递,函数内部隐藏了this指针参数,本类类型的指针。

    (3) 编译器不会为静态成员函数传递this指针。

    2、this特点

    1、非静态成员函数第一个隐藏参数就是thisthis指向调用函数对象的常量指针,常函数。该函数不会去修改成员变量的值。

    2、如果const写在函数后,const其实修饰的是this指针。如下图所示

    class Person
    {
    public:
        // Person * const this
        // const Person * const this
        void show() const
        {
    
        }
    }

    3、当形参与成员变量名冲突的时候,可以用来区分。

    class Demo02
    {
    public:
        Demo02(int a, int b)
        {
            this->a = a;
            this->b = b;
        }
    
        Demo02& get_self()
        {
            return *this;
        }
    
    public:
        int a;
        int b;
    };

    4、如果一个对象被const修饰,常对象只能调用常函数。

    class Demo03
    {
    public:
        Demo03(int a, int b)
        {
            this->m_a = a;
            this->m_b = b;
        }
    
        // 不希望这个函数修改成员变量
        // 可以将成员函数设置为常函数
        // 大部分的成员变量不想修改,有个别的1个变量需要被修改
        // mutable 修饰的成员变量,不受常函数限制
        // const 修饰成员函数,本质上修饰的是 this 指针, Demo03 * const this;
        // const Demo03 * const this;
        // 常对象只能调用常函数
        void show() const
        {
            // m_a = 100;
            m_b = 200;
            cout << m_a << " " << m_b << endl;
        }
    
        void print()
        {
            cout << m_a << " " << m_b << endl;
        }
    
    public:
        int m_a;
        mutable int m_b;
    };
    
    void test02()
    {
        // 常量对象,常对象
        const Demo03 d(100, 200);
        // d.print();
        d.show();
    }

     

     

  • 相关阅读:
    如何让研发团队保持敏捷并不断进步?
    敏捷方法适合什么样的团队?
    规模化敏捷中的“三要”和“三不要”
    敏捷开发中如何使用看板方法创造价值
    4.0 初步预计更新内容
    3.0 环境应用(待更新)
    5.0 Genymotion安装以及基础使用
    2.0 python+appium环境搭建
    1.0 python-client以及ui自动化介绍
    教你一招另辟蹊径抓取美团火锅数据
  • 原文地址:https://www.cnblogs.com/yyslif/p/11755579.html
Copyright © 2011-2022 走看看