zoukankan      html  css  js  c++  java
  • c++const成员函数*

    一:知识点:

    成员函数末尾增加const
    1)该函数被称为常量成员函数
    2)在函数的定义和声明处的末尾都要加const
    3)该成员函数不能修改类中的任何成员(非mutable修饰的任意成员属性)
    4)const 类型的类变量,不能调用非常量成员函数
    5)const和非const类变量,可以调用常量成员函数(const成员函数可被更多场景使用
    6)如果成员属性希望在任意函数中都可以被修改,那么该属性应该被声明为mutable.

    二:例子:

    #include <iostream>
    #include <string>
    using namespace std;

    class Person {
       public:
        int id;
        string name;
        // 在常量成员函数中也可以被修改, mutable和int的前后顺序没关系
        mutable int mt;

       public:
        Person() {
            this->id = 200;
            cout << "wu can gou zao han shu" << endl;
        }

        void PrintPersonConst() const;
        void PrintPerson() {}
        Person(int id);
    };

    void Person::PrintPersonConst() const {
        // mutable属性可在常量函数中被修改
        this->mt = 200;
    }

    int main(int argc, char const* argv[]) {
        const Person pConst;
        // 这里是类常量变量调用了非常量函数,所以会报错
        // pConst.PrintPerson();

        Person p2;
        //类的普通变量可以调用常量函数
        p2.PrintPerson();
        pConst.PrintPersonConst();
    }
  • 相关阅读:
    python初体验-函数(1)
    python初体验-数值类型
    python初体验-常见错误类型
    动态规划专题——passage_1
    七夕——ORMAX(线段树)
    七夕——永远在一起(一维dp)
    动态规划4.4——背包问题
    动态规划4.3——最长公共子串问题
    动态规划4.2——子序列问题
    动态规划4.1——基础动态规划问题
  • 原文地址:https://www.cnblogs.com/qiumingcheng/p/15519357.html
Copyright © 2011-2022 走看看