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;
    }

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

  • 相关阅读:
    IP和java.net.InetAddress类的使用
    Redis(五):几个常用概念
    Redis(一):概述
    mongodb写入策略(WriteConcern)
    mongodb配置详解
    MongoDB优化
    Python 多进程异常处理
    Python多进程编程-进程间协作(Queue、Lock、Semaphore、Event、Pipe)
    Mongodb 性能测试
    把 MongoDB 当成是纯内存数据库来使用(Redis 风格)
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12096102.html
Copyright © 2011-2022 走看看