c++primer之函数重载

  • 如果一个作用域的几个函数名字相同参数列表不同,我们称之为函数重载

下面是注意的一些问题:

重载和const形参

  • 顶层const不影响传入函数的对象。一个顶层的const的形参无法和另一个没有顶层const的形参区分开来。
例:
Record lookup(Phone);
Record lookup(const Phone);  //重复定义了Record lookup(Phone)

Record lookup(Phone*);
Record lookup(Phone* const);  //重复定义了Record lookup(Phone *)
  • 如果形参是某种类型的指针或引用,则通过区分其指向的是常量对象还是非常量对象可以实现函数重载,此时的const是底层的。
 例:
 // 对于接受引用或指针的函数来说,对象的常量引用还是非常量对应的形参不同。
 // 定义了4个独立的重载函数。
 Record lookup(Account&);  // 函数作用于Account的引用
 Record lookup(const Account&); // 新函数,作用于常量引用

 Record lookup(Account*);  // 新函数,作用于指向Account的指针
 Record lookup(const Account&);  // 新函数,作用于指向常量的指针

const_cast 和重载

  • const_cast在重载函数的情景中最有用。
例:
// 比较两个string对象的长度,返回较短的那个引用。
const string &shorterString(const string &s1, const string &s2)
{
    return s1.size() <= s2.size() ? s1 : s2;
}
//这个函数的参数和返回类型都是const string的引用。我们可以对两个非常量的string实参调用这个函数,但返回结果仍然是const string的引用。
  • 我们要定义一个新的shorterString函数,当它的实参不是常量时,得到的结果是一个普通的引用,使用const_cast可以做到这一点。
例:
// 比较两个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);
}

重载和作用域

例:
string read();
void print(const string &);
void print(double);
void foobar(int ival)
{
   bool read = false;   // 新作用域;隐藏了外层的read
   string s = read();   //错误: read是一个布尔值,而非函数;
   // 不好的习惯:通常来说,在局部作用域中声明函数不是一个好的选择。
   void print(int);  //新作用域:隐藏了之前的print
   print("Value:");  //错误:print(const string &)被隐藏掉了
   print(ival);  //正确:当前print(int)可见
   print(3.14);  //正确:调用print(int);print(double)被隐藏掉了
}
// 程序执行过程中,一旦当前作用域找到了所需的名字,编译器就会忽略掉外层作用域中的同名实体。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MachineLP

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值