C + + Class Const member functions

Source: Internet
Author: User

The const keyword can be used in a C + + class to declare a member function that does not modify an object, which you need to be aware of:

1. Const object can only be called by constants member function

2. A const object can call the function

Take the following code as an example to explain:

1 classperson{2      Public:3         voidprint () {4cout<<"I am a common function!"<<Endl;5         }6         voidShow ()Const{7cout<<"I am a const function!"<<Endl;8         } 9 };Ten intMain () { One     ConstPerson A; A a.print (); -}

The result of the program compilation is:

[Error] passing ' const person ' as ' this ' argument of ' void Person::p rint () ' Discards qualifiers [-fpermissive]

It can be understood that when a member function is called on an object, the this pointer is passed in :

1, the common object calls the very member function error reason:

  The Print function prototype is

  Print (person *const a,int i); (pseudo code)

the invocation of the member function a.print () can be equivalent to:

  Print (&a,1); (pseudo code)

that is , this is passed in as an implicit parameter, but The type of a pointer is const person *const;

This can be explained by the knowledge passed by the function parameter, that is, an argument: a constant pointer to a constant object, a parameter: a constant pointer to a normal object, and an argument mismatch (as can be seen from a compilation error).

2, the common object can call the usual member function reason:

  the function prototypes of show can be considered as

  Show (const person*const a,int i); (pseudo code)

that is , the const keyword modifies the incoming object pointer;

At this point, the formal parameter arguments are matched.

In short, this can be judged by the knowledge of the arguments passed.

C + + Class Const member functions

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.