C++ :const修饰成员函数

常函数:

常函数:

成员函数后加const后我们称为这个函数为常函数

常函数内不可以修改成员属性

成员属性声明时加关键字mutable后,在常函数中依然可以修改

属性可修改:

class Person

{

public:

void showPerson()

{

m_A = 100;

}

int m_A;

};

加上 const 属性不可修改:

class Person

{

public:

void showPerson() const

{

m_A = 100;

}

int m_A;

};

具体示例如下:

cpp 复制代码
#include <iostream>
using namespace std;

class Person
{
public:

    //隐含在每一个成员函数内部都有一个this指针
    //this指针的本质是: 一个指针常量, 指针的指向不可修改,值可以修改
    //如果想让指针指向的值也不可以修改,需要声明常函数
    //const Person* const this;
    //在成员函数 后面加const,修饰的是this指向,让指针指向的值也不可以修改
    void showPerson() const   //常函数 (常函数中不允许修改指针指向的值)
    {  
        this->m_B = 100;    //修改加关键字mutable
        //this->m_A = 100;
        //this = NULL; //不能修改指针的指向 Person* const this;
    }
    int m_A;
    mutable int m_B;   //特殊变量,即使在常函数中,也可以修改这个值,加关键字mutable
};
   
void test01()
{
    Person p;
    p.showPerson();

}
int main()
{
    test01();

    system("pause");
    return 0;
}

常对象:

常对象:

声明对象前加const称该对象为常对象

常对象只能调用常函数

cpp 复制代码
class Person
{
public:

    //隐含在每一个成员函数内部都有一个this指针
    //this指针的本质是: 一个指针常量, 指针的指向不可修改,值可以修改
    //如果想让指针指向的值也不可以修改,需要声明常函数
    //const Person* const this;
    //在成员函数 后面加const,修饰的是this指向,让指针指向的值也不可以修改
    void showPerson() const   //常函数 (常函数中不允许修改指针指向的值)
    {  
        this->m_B = 100;    //修改加关键字mutable
        //this->m_A = 100;
        //this = NULL; //不能修改指针的指向 Person* const this;
    }
    void func()
    {
        m_A = 10000;
    }

    int m_A;
    mutable int m_B;   //特殊变量,即使在常函数中,也可以修改这个值,加关键字mutable
};
   
void test01()
{
    Person p;
    p.showPerson();

}

void test01()
{
    const Person p; //常量对象   在对象前面加上const,变为常对象
    //p.mA = 100; //常对象不能修改成员变量的值,但是可以访问
    p.m_B = 100;  //m_B是特殊的值 但是常对象可以修改mutable修饰成员变量

    //常对象只能调用常函数
    p.showPerson();

    //p.func();    常对象不可以调用普通成员函数,因为普通成员函数可以修改属性
}


int main()
{
    test01();

    system("pause");
    return 0;
}
相关推荐
肆忆_13 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星17 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马4 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc4 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼4 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛