BZ易风

导航

 

常函数 

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

结果:

 

posted on 2021-08-21 22:04  BZ易风  阅读(110)  评论(0编辑  收藏  举报