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)被隐藏掉了
}
// 程序执行过程中,一旦当前作用域找到了所需的名字,编译器就会忽略掉外层作用域中的同名实体。

你可能感兴趣的:(c++学习,c++primer,函数重载)