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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM