C++函数默认参数

在定义参数的时候同时给它一个初始值。

void Func(int i = 1, float f = 2.0f, double d = 3.0)
{
    cout << i << ", " << f << ", " << d << endl ;
}


int main(void)
{
    Func() ;                // 1, 2, 3
    Func(10) ;                // 10, 2, 3
    Func(10, 20.0f) ;        // 10, 20, 3
    Func(10, 20.0f, 30.0) ;    // 10, 20, 30

    system("pause") ;
    return 0 ;
}

如果某个参数是默认参数,那么它后面的参数必须都是默认参数

void Func(int i, float f = 2.0f, double d = 3.0) ;void Func(int i, float f, double d = 3.0) ;

但是这样就不可以

void Func(int i, float f = 2.0f, double d) ;

默认参数的连续性能保证编译器正确的匹配参数。所以可以下这样一个结论,如果一个函数含有默认参数,那么它的最后一个参数一定是默认参数。

默认参数可以放在函数声明或者定义中,但只能放在二者之一

.h文件

class TestClass{public:    void Func(int i, float f, double d) ;};

.cpp文件

#include "TestClass.h"void TestClass::Func(int i = 1, float f = 2.0f, double d = 3.0){    cout << i << ", " << f << ", " << d << endl ;}下面的是错误的: void Func(int i=1, float f=2.0f, double d=3.0) ;

void TestClass::Func(int i = 1, float f = 2.0f, double d = 3.0)

{

cout << i << ", " << f << ", " << d << endl ;

}

像上面这样,只能够在TestClass.cpp中调用Func函数。岂不是很痛苦?

默认值可以是全局变量、全局常量,甚至是一个函数。但不可以是局部变量。因为默认参数的调用是在编译时确定的,而局部变量位置与默认值在编译时无法确定。
原文链接: https://www.cnblogs.com/youxin/archive/2012/06/12/2546865.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/52540

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午3:58
下一篇 2023年2月9日 上午3:59

相关推荐