• 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函数。岂不是很痛苦?

     

     默认值可以是全局变量、全局常量,甚至是一个函数。但不可以是局部变量。因为默认参数的调用是在编译时确定的,而局部变量位置与默认值在编译时无法确定。

  • 相关阅读:
    Nginx 前后端分离部署
    SpringBoot 使用外部 Tomcat 容器运行
    SpringBoot 加载 properties
    SpringBoot 启动时加载的自动配置类(SpringFactoriesLoader、SPI)
    微信小程序订阅消息通知
    centos云服务器 部署Gitblit
    centos 安装java
    图片链接控制宽高
    腾讯云部署https
    腾讯云域名绑定
  • 原文地址:https://www.cnblogs.com/youxin/p/2546865.html
Copyright © 2020-2023  润新知