11.3.4重学C++之【const修饰成员函数】

#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;


/*
    4.3.4 const修饰成员函数
        常函数:成员函数后加const(修饰的是this指针,令指针指向的值也不可修改)
            常函数内不可修改成员属性
            成员属性声明时加关键字mutable后,在常函数中依然可以修改
        常对象:声明对象前加const
            常对象只能调用常函数
*/


class Person{
public:
    int a;
    mutable int b;

    Person(){

    }

    void show_person(){
        a = 100;
        this->a = 100;
         // this指针是隐含每一个非静态成员函数内的一种指针,其不需定义,课直接使用
        // this指针的本质是指针常量,故该指针的指向不可修改
        // 在test()案例中,该this指针:Person * const this,其指向p
    }

    /*
    void show_person()const{ // 常函数
        a = 100; // 报错
        this->a = 100; // 报错
        // 此时 this:const Person * const this
    }
    */

    void show_person1()const
    {
        b = 100; // ok
        this->b = 200;
    }
};


void test(){
    Person p;
    p.show_person();
    p.show_person1();
}

void test2(){
    const Person p1; // 常对象
    //p1.a = 100; // 报错
    p1.b = 300; // ok

    //p1.show_person(); // 报错
    p1.show_person1(); // ok 常函数
}


int main(){
    test();
    test2();

    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/HAIFEI666/article/details/114875100