常函数
class phone{
int num;
void getphone(){
num = 10;
this = NULL;
}
}
当在成员函数后面加入了一个const之后
class phone{
void getphone() const{
}
int num;
multable int num2;
}
常对象
#include <iostream>
using namespace std;
class phone {
public:
void getphone() const {
}
int num;
mutable int num2;
};
void main() {
const phone p;
p.num = 10;
p.num2 = 10;
}
注意事项:常对象只能调用常函数,常函数只能修改mutable
class phone {
public:
void getphone1() const {
num = 3;
num2 = 3;
}
void getphone2() {
num = 3;
num2 = 3;
}
int num;
mutable int num2 = 1;
};
void main() {
const phone p1;
p1.getphone1();
p1.getphone2();
phone p2;
p2.getphone1();
p2.getphone2();
}
总结
1、常对象只能调用常函数
普通对象两者都能调用
2、常函数只能修改mutable修饰的变量
普通函数两者都能修改