出现在作用域中的两个函数,如果具有相同的名字而形参表不同,则称为重载函数。
重载函数在作用域方面特别要注意:
string init();// the name init has global scope void fcn() { int init = 0;//init is local and hides global init string s = init();//error: global init is hidden }
上面 的函数里面的fcn()函数就覆盖了全局函数init();
再看下例:
void print(const string &); void print(double );//overloads the print function void fooBar(int ivar) { void print(int);//new scope:hides previous instances of print print("Value :");//error: print (const string &)is hidden print(ival);//ok:print(int )is visible print(3.14)//ok:calls print(int);print(double)is hidden }
因为在函数fooBar()里面声明了print(int)函数,所以调用print函数时就会找具有int类型的形参,这样前面的声明的重载函数就会被隐藏。
当传递一个double参数时,编译器会隐式的转换为int参数进行匹配。