C + + Const this pointer

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.