重载函数的调用匹配依次按照下列规则判断:
1. 精确匹配: 参数正好匹配无需转换,或者只是做微不足道的变动:
数组名 到 指针,函数名 到 指向函数的指针,某个变量a 到 常量const a 等等;
2. 提升匹配: 即 float 到 double , 整数匹配(如bool 到 int , char到int , short到int);
3. 升级规则:(最低类型)bool -> char -> unsigned char -> short -> unsigned short -> int -> unsigned int -> long int ->unsigned long -> float -> double -> long double ;
注意 : 把值从较高类型转换到较低类型,会引起数据的丢失。
Argument Promotion Rules
Sometimes, argument values that do not correspond precisely to the parameter types in the
functionprototypecanbeconvertedbythecompilertothepropertypebeforethefunction
is called. These conversions occur as specified by C++’s promotion rules. The promotion
rulesindicatetheimplicitconversionsthat thecompilercan performbetweenfundamental
types. An int can be converted to a double .
However, a double converted to an int trun-
cates the fractional part of the double value. Keep in mind that double variables can hold
numbers of much greater magnitude than int variables, so the loss of data may be consid-
erable. Values may also be modified when converting large integer types to small integer
types (e.g., long to short ), signed to unsigned or unsigned to signed. Unsigned integers
range from 0 to approximately twice the positive range of the corresponding signed type.
Thepromotionrulesapplytoexpressionscontainingvaluesoftwoormoredatatypes;
such expressions are also referred to as mixed-type expressions. The type of each value in
a mixed-type expression is promoted to the “highest” type in the expression (actually a
temporary version of each value is created and used for the expression—the original values
remainunchanged).Promotionalsooccurswhenthetypeofafunctionargumentdoesnot
matchthe parameter typespecifiedin thefunction definition or prototype. Figure 6.6 lists
the fundamental data types in order from “highest type” to “lowest type.”