常函数:
- 成员函数后加const后我们称为这个函数为常函数
- 常函数内不可以修改成员属性
- 成员属性声明时加关键字mutable后,在常函数中依然可以修改
常对象:
- 声明对象前加const称该对象为常对象
- 常对象只能调用**常函数**
#include <bits/stdc++.h>
using namespace std;
class Person{
public:
Person(int num,int age):m_Num(num),m_Age(age){
cout << "Person参数列表的构造" << endl;
}
void showPerson() const{
this->m_Age = 20;
}
~Person(){
cout << "Person析构函数的调用" << endl;
}
public:
int m_Num;
mutable int m_Age;
};
Person func(Person per){
return per;
}
int main(){
Person person2(10,30); // 括号法调用有参构造函数
cout << "m_Num = " << person2.m_Num << endl;
cout << "m_Age = " << person2.m_Age << endl;
person2.showPerson();
cout << "m_Age = " << person2.m_Age << endl;
return 0;
}