#include<iostream>
using namespace std;
class Person
{
public:
int m_A;
mutable int m_B;//加上mutable后,在const常函数还是可以修改
public :
Person(int a, int b)
{
m_A = a;
m_B = b;
}
//const Person * const this相当于下面的const
void showPerson() const
{
this->m_B = 100;
//this->m_A = 100;错误,const以后不能修改
//this = NULL;错误,this指针不可以i需改指针的指向
}
void func()
{
}
};
//常函数
void test01()
{
Person p(10,20);
p.showPerson();
}
//常对象
void test02()
{
const Person p(20,30);
//p.m_A = 100;报错,不能修改
p.m_B = 100;//mutable的可以改
cout << p.m_B;
p.showPerson();
//p.func();报错,常对象只能调用常函数。不能调用普通成员函数,是因为普通函数可以调用普通成员变量
}
int main() {
test02();
}
C++中const修饰成员函数
最新推荐文章于 2024-08-03 23:00:42 发布