What does the const after const this pointer method list mean?
Answer: You cannot modify member variables in a method
class Test{public: void fun()const{ //data = 10;//编译不过,因为有const关键字,所以不可以修改this指针所指向的内容 }private: int data;};
Note the point:
- It is possible to call the Const method in a non-const method
- It is possible to call the Const method in the Const method
- It is not possible to call a non-const method in a const method .
Reason: This
pointer.
Because the this pointer in the non-const method has a const limit, it is not possible to give a non-const method A this pointer without a const restriction when calling a non-const method in a const method.
#include <iostream>using namespace std;class Test{public: Test(int d = 0) : data(d){} void a()const{ b(); } //如果去掉方法b的const关键字,编译无法通过 void b()const{ } ~Test(){}private: int data;};int main(){ Test t(10);}
C + + Const this pointer