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;    // 返回正常退出
    }

    结果:

  • 相关阅读:
    再次尝试windows下msys+MinGW编译ffmpeg
    iOS设备的硬件适配 (关于armv6, armv7, armv7s ) <转>
    vmware虚拟机下ubuntu 13.04使用zeranoe脚本交叉编译ffmpeg
    vmware 8下ubuntu 13.04安装vmware tools
    ubuntu下使用脚本交叉编译windows下使用的ffmpeg + X264
    网上看来的
    ffmpeg关于aac解码
    iOS阶段学习第15天笔记(NSDate操作)
    iOS阶段学习第15天笔记(NSDictionary与NSMutableDictionary 字典)
    iOS阶段学习第15天笔记(NSArray与NSMutableArray 数组)
  • 原文地址:https://www.cnblogs.com/yifengs/p/15170724.html
Copyright © 2011-2022 走看看