C++重载函数的注意事项
#include<iostream> using namespace std; /** * 函数重载注意事项 * 1,函数重载和引用参数 * 变量引用和常量引用被编译器视为不同的类型, 对于两个函数名相同的函数的某个参数, 一个是变量引用类型, 一个是常量引用类型, 可以重载 * 此时调用时, 给该参数传入变量即调用使用变量引用的参数的函数, 传入常量则调用使用常量引用的参数的函数 * 2,函数重载和默认参数 * 最好不要在重载函数中使用默认参数, 很容易导致语句的二义性, 导致程序运行出错 */ //函数重载和引用类型参数 //变量引用 void func(int &a){ cout << "call function func(int &a)!" << endl; } //常量引用 void func(const int &a){ cout << "call function func(const int &a)!" << endl; } //使用默认函数的重载函数 void func2(int a, int = 10){ cout << "call function func(int a, int = 10)!" <<endl; } void func2(int a){ cout << "call function func(int a)!" <<endl; } int main() { int a = 10; /*func(a);*/ //output: //call function func(int &a)! /*func(10);*/ //output: //call function func(const int &a)! /*func2(10);*/ //Call to 'func2' is ambiguous system("pause"); return 0; }
路漫漫其修远兮,吾将上下而求索。