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();
    }

     

     

  • 相关阅读:
    windows7 下 oracle 10g服务端如何安装?
    DOM模块支持测试
    获取css属性
    在webstorm启动nginx服务器
    获取link链接
    innerText
    外部动态加载javascript
    外部动态加载css
    冒泡排序
    Nodelist
  • 原文地址:https://www.cnblogs.com/yyslif/p/11755579.html
Copyright © 2011-2022 走看看