zoukankan      html  css  js  c++  java
  • const修饰成员函数(常函数 )和常对象

    常函数 

    void func() const {} 常函数

    修饰是this指针 const Type * const this, 不能修改this指针指向的值

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    using namespace std;
    
    class Person
    {
    public:
        Person()
        {
            //构造中修改属性
            //this永远指向本体
            //相当于 Person * const this  不允许修改指针的指向
            this->m_A = 0;
            this->m_B = 0;
        }
    
        void showInfo() const   //const加在函数的括号后面表示常函数 不允许修改指针指向的值 因为void showInfo()相当于void showInfo(Person * const this)
        {                        //所以在函数后再加const 相当于const Person* const this 既不能修改指针的指向 也不能修改指针指向的值
            this->m_A = 1000;    //error
        }
    
        int m_A;
        int m_B;
    };
    
    int main()
    {
        system("Pause");        //阻塞功能
        return EXIT_SUCCESS;    // 返回正常退出
    }

    常对象

    用const修饰的对象,不允许修改属性

    不可以调用普通的成员函数

    可以调用常函数

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    using namespace std;
    
    class Person
    {
    public:
        Person()
        {
            //构造中修改属性
            //this永远指向本体
            //相当于 Person * const this  不允许修改指针的指向
            this->m_A = 0;
            this->m_B = 0;
        }
    
        void showInfo() const   //const加在函数的括号后面表示常函数 不允许修改指针指向的值 因为void showInfo()相当于void showInfo(Person * const this)
        {                        //所以在函数后再加const 相当于const Person* const this 既不能修改指针的指向 也不能修改指针指向的值
            //this->m_A = 1000;    //error
            this->m_B = 1000;    //可以修改
        }
        void show()
        {
    
        }
    
        int m_A;
        mutable int m_B;    //就算是常函数,也想要修改 需要加mutable关键字
    };
    
    void test201()
    {
        const Person p;    //常对象 不允许修改属性
        //p.show();        //常对象不可以调用普通成员方法
        p.showInfo();    //常对象可以调用常函数 有mutable关键字的属性还是可以被修改
        cout << "m_B = " << p.m_B << endl;
    }
    
    int main()
    {
        test201();
        system("Pause");        //阻塞功能
        return EXIT_SUCCESS;    // 返回正常退出
    }

    结果:

  • 相关阅读:
    在SplendidCRM中添加用户控件
    SPendidCRM:给HK的ImageInfoEntryEditView增加一个checkbox,用于判断特殊类型的PODS记录
    html button 跳转ASP.NET页面跳转技术总结
    让<li>不显示超出内容,显示... (编程方法和CSS方法)
    SplendidCRM Popup.aspx的hyperlink字段配置的易错点
    asp.net 个别页面URL参数出现中文乱码的解决方法
    解决:工具箱里边没了Dev控件
    DevControlgridview的属性说明 (转)
    DevControlgridview的属性说明 (转)
    VM如何设置U盘启动
  • 原文地址:https://www.cnblogs.com/yifengs/p/15170724.html
Copyright © 2011-2022 走看看