class BadString
{
public:
BadString(char const*);
char& operator[] (size_t);
operator char* ();
};
BadString str("correkt" );
str[5] = ''c'';
上面的str[5]=''c''能正确的选择出匹配的函数吗?让我们来仔细的看看C++函数重载时候的匹配等级
1.Perfect match. The parameter has the type of the expression, or it has a type that is a reference to the type of the expression (possibly with added const and/or volatile qualifiers).这种情况比较好理解
int foo(int);
int foo(float);
foo(5);//毫无疑问的是满足这个匹配条件的,所以这个匹配是Perfect match;
但这里要注意到就是const引用的问题,那就是非const首选是左值,const首选是右值.
int foo(int& );
int foo(const int& );
int t=foo(1);//选择const int&
int t1=foo(t);//选择int&
如果上面的那个例子里面再加int foo(int),那么两个函数调用都将不能得到最好的匹配从而导致编译错误.
2.Match with minor adjustments. This includes, for example, the decay of an array variable to a pointer to its first element, or the addition of const to match an argument of type int** to a parameter of type int const* const*.直接来看一个例子
class A
{
public:
A(char*);
};
int foo(A);
int foo(char*);
char t[20];
foo(t);//调用foo(char*),第一个函数匹配等级低于这个函数
3.Match with promotion. Promotion is a kind of implicit conversion that includes the conversion of small integral types (such as bool, char, short, and sometimes enumerations) to int, unsigned int, long or unsigned long, and the conversion of float to double.这部分就是类型的提升,这种情况也碰到比较多
int foo(int);
int foo(char);
foo(ture);//选择foo(int),后一个需要standard conversions,比foo(int)的匹配等级要低
4.Match with standard conversions only. This includes any sort of standard conversion (such as int to float) but excludes the implicit call to a conversion operator or a converting constructor.这里需要注意的是不包括构造函数和转换操作符的隐式转换(包含在下面的等级)
class A
{
public:
A(int);
};
int foo(float);
int foo(A);
foo(5);//调用foo(float),第二个函数的调用需要使用构造函数的转换.
5.Match with user-defined conversions. This allows any kind of implicit conversion.这里就是上面排除了的那些转换了.
class A
{
public:
A(int);
};
int foo(A);
int foo(...);
foo(5);//这里将调用foo(A),因为foo(...)拥有最低的匹配等级
6.Match with ellipsis. An ellipsis parameter can match almost any type (but non-POD class types result in undefined behavior).终于到了...,这个没什么好说的,说句玩笑话,有时候有得调用总比没有强.
还有一个最后的最强的原则就是For one candidate to be considered better than another, the better candidate cannot have any of its parameters be a worse match than the corresponding parameter in the other candidate.俗话就是一好百好.
int foo(int,double);
int foo(long,int);
foo(1, 2);//这个不能得到最好的匹配从而导致编译错误.

浙公网安备 33010602011771号