• [C++] const和mutable关键字使用方法


    const 修饰的变量为常成员变量,表示此变量不能被修改赋值,并且构造函数中只能用初始化列表的方式初始化,其他初始化方式都是错误的

    const 修饰的函数为常成员函数,表示此函数中只能读取成员变量,不能修改成员变量

    const 修饰的对象为常对象,常对象保护了对象中所有的数据成员不能被任何函数访问和修改,只能使用常成员函数来访问。

    如果一个对象被声明为常对象,它只能调用该对象的 const 型成员函数。

    常对象定义格式:

    // 下面两种方式都可以
    const 类名 对象名;
    类名 const 对象名;

    mutable 是为了突破 const 的显示而设置的,被 mutable 修饰的变量,将永远可变,即使在 const 修饰的函数中。

    #include "iostream"
    
    using namespace std;
    
    class Student {
    private:
        const int a;
        const int b = 34;
        int c = 78;
        mutable int d;
    public:
        // 只能用初始化列表的方式初始化常量
        explicit Student(int a) : a(a) {
            // 这种方式初始化常量是错误的
            //this->b = 56;
        }
    
        void print() const {
            // 常成员函数中不能修改成员变量
            //this->c = 78;
            // mutable修饰的变量可以在常成员函数中修改
            this->d = 90;
            cout << a << " " << b << " " << c << " " << d << endl;
        }
    
        void print1() {
            cout << a << " " << b << " " << c << " " << d << endl;
        }
    };
    
    int main(void) {
    
        Student stu1(12);
        stu1.print();
        stu1.print1();
        
        const Student stu2(11);
        // 常对象只能调用常成员函数
        stu2.print();
        // 错误
        //stu2.print1();
    
        return 0;
    }
  • 相关阅读:
    No-3.Linux 终端命令格式
    No-2.常用 Linux 命令的基本使用
    No-1.文件和目录
    No-7.运算符
    No-6.If语句
    No-5.变量的命名
    YOLOv4详细分析 | 细数当前最佳检测框架小细节(附论文及源码下载)
    案例】S7-200SMART 实时时钟如何在MCGS触摸屏上显示并写入
    卡尔曼滤波:从入门到精通
    mmdetection最小复刻版(七):anchor-base和anchor-free差异分析
  • 原文地址:https://www.cnblogs.com/lialong1st/p/12066937.html
Copyright © 2020-2023  润新知