zoukankan      html  css  js  c++  java
  • c++之const修饰成员函数

    常函数:

    • 成员函数后加const后我们称这个函数为常函数;
    • 常函数不可以修改成员属性
    • 成员属性声明时加关键字mutable后,在常函数中依然可以修改

    常对象:

    • 声明对象前加const
    • 常对象只能调用常函数

    常函数:

    #include<iostream>
    using namespace std;
    class Person {
    public:
        int age;
        mutable int tmp;//用mutable修饰的为特殊变量,可以在常量函数中修改
        void showPerson() const{
            //this指针的本质是指针常量,指针的指向是不可以修改的
            this = NULL;
            //即Person* const this;
            //在函数后面加了const之后,变成const Person* const this
            //此时,既不可以修改指向,也不可以修改值
            this->age = 100;
            this->tmp = 200;
        }
    };
    int main() {
        Person p;
        p.showPerson();
        system("pause");
        return 0;
    }

    说明:红色标注的是编译报错的,紫色标注的是可以成功编译的。

    常对象:

    #include<iostream>
    using namespace std;
    class Person {
    public:
        int age;
        mutable int tmp;//用mutable修饰的为特殊变量,可以在常量函数中修改
        void showPerson() const{
            cout << "这是常函数" << endl;
        }
    };
    void test() {
        const Person p;//在对象前加const,变为常对象
        //常对象不能调用普通成员变量
        p.age = 10;
        //特殊变量,在常对象下也可以修改
        p.tmp = 20;
        //常对象只能调用常函数
        p.showPerson();
    }
    int main() {
        test();
        system("pause");
        return 0;
    }

    说明:红色标注的是编译报错的,紫色标注的是可以成功编译的。

  • 相关阅读:
    解决全局变量共享---C语言的extern关键字用法
    VIM学习笔记
    测试博客
    docker容器中安装vi
    docker中安装Jenkins
    Jenkins Pipeline+Maven+Gitlab持续集成构建问题集锦
    jenkinsapi操作Jenkins,提示:No valid crumb was included in the request
    python语言的jenkinapi
    Jenkins Pipeline+Maven+Gitlab持续集成构建
    windows中卸载Jenkins
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12096102.html
Copyright © 2011-2022 走看看