【问题标题】:Must default function parameters be constant in C++?C++ 中的默认函数参数必须保持不变吗?
【发布时间】:2010-09-24 23:51:46
【问题描述】:
void some_func(int param = get_default_param_value());

【问题讨论】:

    标签: c++


    【解决方案1】:

    他们不必是!默认参数可以是特定限制内的任何表达式。每次调用函数时都会对其进行评估。

    【讨论】:

      【解决方案2】:

      默认参数可以是完整表达式集的子集。它必须在编译时和默认参数的声明处绑定。这意味着它可以是函数调用或静态方法调用,并且可以采用任意数量的参数,只要它们是常量和/或全局变量或静态类变量,但不能是成员属性。

      它在编译时和函数声明的地方被绑定的事实也意味着如果它使用一个变量,即使另一个变量在原来的位置遮蔽了原始变量,也会使用该变量。函数调用。

      // Code 1: Valid and invalid default parameters
      int global = 0;
      int free_function( int x );
      
      class Test
      {
      public:
         static int static_member_function();
         int member_function();
      
         // Valid default parameters
         void valid1( int x = free_function( 5 ) );
         void valid2( int x = free_function( global ) );
         void valid3( int x = free_function( static_int ) );
         void valid4( int x = static_member_function() );
      
         // Invalid default parameters
         void invalid1( int x = free_function( member_attribute ) ); 
         void invalid2( int x = member_function() );
      private:
         int member_attribute;
         static int static_int;
      };
      
      int Test::static_int = 0;
      
      // Code 2: Variable scope
      int x = 5;
      void f( int a );
      void g( int a = f( x ) ); // x is bound to the previously defined x
      void h()
      {
         int x = 10; // shadows ::x
         g(); // g( 5 ) is called: even if local x values 10, global x is 5.
      }
      

      【讨论】:

      【解决方案3】:

      David Rodríguez - dribeas answear 很棒,但没有提供解决方案。
      看起来好像没有解决办法。

      解决方法很简单:用函数/方法重载替换默认参数。

      void some_func(int param);
      void some_func() {
          some_func(get_default_param_value());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-15
        • 1970-01-01
        • 2013-09-09
        • 2012-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多