1 如果用const修饰一个类的成员方法,这个方法就不能修改这个类的成员变量,也不能调用这个类的非const的成员方法。如下:
class A05 {
public:
void run() const {
i++;
cout << "index:" << i << endl;
}
private:
int i { 0 };
};
run方法是const的,此方法体内不能对成员变量修改,因此i++这句编译报错。
class A05 {
public:
void run() const {
f0();
cout << "index:" << i << endl;
}
void f0() {
cout << "f0:" << i << endl;
}
private:
int i { 0 };
};
由于run方法调用了非const的方法f0(),所以编译报错。
2 const修饰一个类的成员变量,这个变量在初始化之后就不能修改,如下:
class A05 {
public:
A05(int index):
number(index) {
cout << "A05:" << number << endl;
}
void f0(int j) {
this->number = j;
cout << "f0:" << number << endl;
}
private:
const int number { 0 };
};
方法f0()想修改number的值,不被允许,编译报错。