The constant member function in C + +

Source: Internet
Author: User

Code:

1#include <iostream>2 3 using namespacestd;4 5 classa{6      Public:7         voidfunc1 () {8cout<<"func1"<<Endl;9         }Ten         voidFunc1 ()Const{ Onecout<<"Const FUNC1"<<Endl; A         } -         voidFunc2 ()Const{ -cout<<"Const FUNC2"<<Endl; the         } -         voidfunc3 () { -cout<<"func3"<<Endl; -         } + }; -  + intMain () { A  at A A1; - a1.func1 (); - A1.func2 (); -  -AConstA2; - a2.func1 (); in     //a2.func3 (); Compile error -  to     return 0; +}

Output:

Func1const Func2const func1

Analysis:

1. A regular object can only invoke the constant member function.
2. Normal objects can call all member functions.
3. When a member function is called on an object, the compiler assigns the address of the object to the this pointer, and then calls the member function, which is implicitly used by the this pointer each time the member function accesses the data member.

4. When a member function is called, it is automatically passed an implied argument, which is a pointer to the object where the member function resides.
5. In C + +, the This pointer is implicitly declared as: X *const This, which means that the this pointer cannot be assigned a value;
In the const member function of the X class, the type of the this pointer is: const x* const, which indicates that the object pointed to by this pointer is non-modifiable (that is, the data member of such an object cannot be assigned to a value operation);
6. Because this is not a regular variable, the address of this cannot be obtained.

A more detailed explanation: http://blog.csdn.net/zhuyingqingfen/article/details/31751111

It is important to note that the constant member function cannot modify the object's member variables.

The constant member function in C + +

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.