zoukankan      html  css  js  c++  java
  • 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函数。岂不是很痛苦?

     

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

  • 相关阅读:
    Jedis 源代码阅读一 —— Jedis
    Java中的${pageContext.request.contextPath}
    VMware Workstation 12 安装mac os x 10.11
    机器学习——朴素贝叶斯分类器
    Codeforces 138C(区间更新+离散化)
    Threejs 官网
    深刻理解Nginx之Nginx完整安装
    Apache + Tomcat 负载均衡 session复制
    小P寻宝记——好基友一起走
    C++数值类型极限值的获取
  • 原文地址:https://www.cnblogs.com/youxin/p/2546865.html
Copyright © 2011-2022 走看看