C++ -- 函数参数的缺省

C++函数参数的缺省

有一些参数的值在每次函数调用时都相同,书写这样的语句会使人厌烦。C++语言采用参数的缺省值使书写变得简洁(在编译时,缺省值由编译器自动插入)。

使用规则:

  1. 参数缺省值只能出现在函数的声明中,而不能出现在定义体中。

  2. 如果函数有多个参数,参数只能从后向前缺省。
    正确的示例如下:

void Func(int x, int y=0, int z=0);

错误的示例如下:

void Func(int x=0, int y, int z=0); 

要注意,使用参数的缺省值并没有赋予函数新的功能,仅仅是使书写变得简洁一些。它可能会提高函数的易用性,但是也可能会降低函数的可理解性。所以我们只能适当地使用参数的缺省值,要防止使用不当产生负面效果。下面的示例中,不合理地使用参数的缺省值将导致重载函数output产生二义性。

#include <iostream>

void output(int x);
void output(int x, float y=0.0);
 
int main(int argc, const char argv[])
{
    int x=1;
    float y=0.5;
	// output(x);          // error! ambiguous call
    output(x,y);        // output int 1 and float 0.5
    return 0;
}
 
void output(int x)
{
    cout << " output int " << x << endl ;
}
 
void output(int x, float y)
{
    cout << " output int " << x << " and float " << y << endl ;
}
// 由于参数缺省的函数与重载的函数产生了冲突,而导致二义性

感谢

发布了64 篇原创文章 · 获赞 6 · 访问量 5561

猜你喜欢

转载自blog.csdn.net/weixin_45494811/article/details/104117223