Const-based overloading

Source: Internet
Author: User

C + + does not allow the use of the difference between the top-level const to define overloaded functions, such as the following practice will cause duplicate declarations, because a function called a const int can accept an argument of int (implicitly type conversion)


void print (int) void print (const int)//Duplicate declaration, cannot differentiate void print (int*) void print (INT*CONST)//duplicate declaration from void Print (int), cannot be associated with void Print (Int*const) differentiate


But C + + allows it to be overloaded by distinguishing whether the member function is const, for example, there is no problem with the following approach:

Class Screen {public:    //Two different functions, no duplicate declaration of    Void print () const;    void print ();}

The reason this code does not cause problems is that the const here actually contains the underlying const, not just the top-level const (that is, both the underlying const and the top-level const). The following pseudo-code is a more visually descriptive explanation of why a duplicate declaration problem does not occur:

std::string person::getname () const;//the above sentence is equivalent to the statement://std::string person::getname (const person* const);//(Note: actually C + + There is no such form of declaration, but it is easy to understand and can be understood as a declaration of this form)








Const-based overloading

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.