C ++ const member functions

Source: Internet
Author: User

C ++ const member functions
First fact:

In a certain type, two functions can be declared and defined in this way, and can be overloaded)

void pa(){    cout<<"a"<<endl;}void pa() const{    cout<<"b"<<endl;}

The above statement is correct.

Based on this fact, I thought about its mechanism.

Experiments show that,

The second fact:

A common function (not a member function of a class) can be overloaded as follows ):

void fun(const int &a){    cout<<a<<endl;}void fun(int &a){    cout<<a<<endl;}

The second fact shows that if the function parameter is of the [Reference Type], [const] and [without const] can be reloaded.

Third fact:

A common function (not a member function of a class) can also be overloaded using a pointer like this ):

void test(const int* a){    cout<<*a<<endl;}void test(int* a){    cout<<*a<<endl;}

The third fact shows that the pointer can also be reloaded by adding const and without const.

Analyze the first fact:

According to c ++ primer, a member function itself has an implicit parameter: ClassName * const this // this parameter is irrelevant to the topic of this article.

But let's explain this const first. That is to say, a pointer itself can no longer point to others but to itself.

Therefore, you cannot change the value of this in the class,

This = 0; // error!

Let's talk about these two class member functions:

void pa();void pa() const;

It can be fully written and become a pseudo-code that is easy to understand, like this:

void pa(ClassName *const this);void pa(const ClassName *const this);

First, I have already said this.

The second is a special syntax provided by c ++ to the user, that is, the member function adds const, which is actually added to the front of the implicit parameter this.

Okay. Summary:

This is why member functions can be overloaded by adding the const modifier.

 

Related Article

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.