Functions that have the same name but different parameter lists and that appear in the same scope are overloaded
- It is an error for two functions to differ only in terms of their return types
⚠️ 别用 cast 来 call func,如果真的需要这么做,你应该改进的函数。
Functions Matching
除了看最基本的参数个数,参数类型之外,当遇到 conversion时,the viable function is:other than error
- 它的 argument 契合度不比别的函数的差(大于等于)
- 它的 argument 契合度至少有一个比别的函数的强(大于)
Conversions are Ranked as Follows: Implicit Conversions
- exact match
- 就是完全一样
- 数组或函数转变为对应指针
- top-level
const
is added to or discarded from
- low-level
const
conversion- 当两个都有的时候,会区分出 the best match
- promotion
- 注意 interal type 总是会先变成
int
当不是 exact match。所以'a' int short
会匹配int
- convention 之间是没有优先级,所以
3.14 long float
is ambiguous.
- 注意 interal type 总是会先变成
- arithmetic or pointer conversion
- class-type conversion
- A parameter that has a top-level const is indistinguishable from one without a top-level const. (But low-level const is distinguishable.
More details in Funcs Matching.)
虽然当只有const的参数表时,nonconst也能match,但是当两个都有的时候,就会区分了(不知道是不是跟那个“tmp”有关。猜对了!就是和这个有关)
const_cast
and Overloading
/* example */
const string &shorterString(const string &s1, const string &s2){
return s1.size() <= s2.size() ? s1 : s2;
}
string &shorterString(string &s1, string &s2){
auto &tmp = shorterString(const_cast<const string&>(s1),
const_cast<const string&>(s2));
return const_cast<string&>(r);
}
- 如果我们不用const,那我们就传不进const的object,也传不进literal
- 如果只用const,那传进去的是nonconst结果出来的是const,这多不好!
- 这个方法确保了:如果进去的是nonconst,那么cast on or away the const is legal. 如果进去的是const,那么不会运行第二个函数。所以是安全的
Overloading and Scope
其实跟变量的情况非常类似
string read(); // note that the name of a func is also a name
void print(const string &);
void print(double); // overload
void fooBar(int ival){
bool read = false; // new scope: hide the outer read
string s = read(); // error: bool is not a func
void print(int); // new scope: hide the outer two func
}
- Names do not overload across scopes. (串域不会overload)
- In C++, name lookup happens before type checking.
term | mean |
---|---|
candidate functions | same name and is visible at the point of the call |
viable functions |