【足迹C++ primer】12、函数重载

函数重载

main函数不能重载

定义重载函数

Record lookup(const Account&);  //Account是一个类型
Record lookup(const Phone&);
Record lookup(const Name&);
Account acct;
Phone phone;
Record r1=lookup(acct);
Record r2=lookup(phone);

重载函数应该是参数个数和参数类型不同

重载和const形参

一个拥有顶层const的形参无法和另一个没有顶层const的形参区分开来。
另一方面,如果形参是某类型的指针或引用,则通过区分其指向的是常量对象还是非常量对象可以实现函数重载,此时const是底层的

const_cast和重载

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

不论这样返回都是const的string常量
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是用来解常量的

调用重载的函数

三种情况:完美匹配,不匹配,二义性调用

1、重载与作用域

string read();
void print(const string &);
void print(double); //重载print函数
void fooBar(int ival)
{
    bool read = false;  //新作用域,隐藏外面的read
    //在局部作用域里面声明函数不是个好想法
    void print(int);
  //  print("Value: ");
    print(ival);
    print(3.14);    //调用void print(int);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值