函数重载
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);
}