【共读Primer】54.[6.4]函数重载--const_cast和重载 Page209

const_cast和重载

在下面的第一个函数中我们使用是否const的字符串都可以调用,

但是返回值也都是const string &。

如果我们需要一个返回后可以被修改的值,也就是左值,那么我们就需要用到第二个函数。

第二个函数中有const_cast对字符串进行从非const到const 

再由const到非const的转换。

我们可以看出以下的这种调用是安全的。

而第二个函数解决了我们的调用后返回值可修改的问题。

const string & shorterString(const string &s1, const string &s2)
{
    return s1.size() <= s2.size() ? s1 : s2
}



string & shorterString(string &s1, string &s2)
{
    auto & r = shorterString(const_cast<const string&>(s1),
                                       const_cast<const string&>(s2));
    return const_cast<string&>(r);
}

以上就是在实际的编程中对const_cast的一个实际的使用。

 

调用重载函数

在编译器进行函数调用的时候会进行一系列的匹配过程。

这个匹配过程叫做重载确定。

编译器找到一个最佳匹配的函数,则生成代码调用

找不到任何一个函数与调用的实参匹配,发生无匹配错误。

找到多个匹配项则会有二义性调用

 

posted @ 2018-09-09 14:25  chattyku  阅读(272)  评论(0)    收藏  举报