c++知识点之 --函数参数默认值
c++中参数的形参列表中的形参是可以有默认值的。默认值必须是从右向左依次赋默认值。函数在主函数下面定义需要声明,声明时给默认值,实现时不需要给了。
//void fun(int a = 1, int b = 2, int c = 3)
//{
// cout << a << b << c << endl;;
//}//函数在主函数下面定义需要声明 声明时给默认值,实现时不需要给
void fun(int a = 1, int b = 2, int c = 3);int main()
{fun(1);fun(1, 22);fun(1, 22, 333);return 0;
}void fun(int a, int b, int c)
{cout << a << b << c << endl;;
}
在一个类中,当无参数的构造函数和带默认参数的构造函数重载时,有可能产生二义性。
//1.引用作为传递条件void func(int& a)
{cout << "func(int a)调用" << endl;
}
void func(const int& a)
{cout << "func(const int &a)调用" << endl;
}//2.函数重载碰到函数默认参数void func2(int a, int b = 10)
{cout << "fun2(int a,int b=10)调用" << endl;
}void fun2(int a)
{cout << "fun2(int a)调用" << endl;
}
int main()
{int a;func(a);//调用无constfunc(10);//调用有constfunc2(10);return 0;
}