首页 > 编程语言 > 详细

c++之const修饰成员函数

时间:2019-12-25 13:48:28      阅读:110      评论:0      收藏:0      [点我收藏+]

常函数:

  • 成员函数后加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++之const修饰成员函数

原文:https://www.cnblogs.com/xiximayou/p/12096102.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!