link: https: //zhuanlan.zhihu.com/p/23820281
Source: know almost
copyrighted by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
statement:
- The content in the article is collected and compiled from "C++ Primer Chinese Edition (5th Edition)", and the copyright belongs to the original book.
- The original book has more detailed and wonderful interpretations, please buy genuine books for learning.
- This article is only for learning and communication, any form of reprinting is prohibited
- In the same scope
- Same function name
- Different parameter list
Where the parameter list is different means
- Different amount of shape parameter
- Or the same number but different parameter types
note:
- Type aliases do not constitute overloads
- Top-level const does not constitute overload
MZF: We should not pursue grammar and force overloading. Function names should be as good as possible.
const_cast and overloading
If the function's formal parameters and return value are underlying const, we can use const_cast and overloading to create a non-const version of the function
When writing overloaded functions, pay attention to modifying the const of the formal parameters, otherwise it will not constitute an overload
const string &Test( const string &s1 )
{
return s1;
}
string &Test( string &s1 )
{
auto &sResult = Test( const_cast<const string&>( s1 ) );
return const_cast<string &>( sResult );
}
It may not be obvious here. If the implementation of Test is long, the advantages of this technique will be obvious.
Overloading and scope
Only in the same scope will constitute an overload
The function declared in the inner scope will hide the entity of the same name declared in the outer scope (it is no different from the variable)