繁体   English   中英

C++ 中的默认函数参数必须是常量吗?

[英]Must default function parameters be constant in C++?

void some_func(int param = get_default_param_value());

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

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

// 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.
}

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

David Rodríguez - dribeas answear 很棒,但没有提供解决方案。
看起来似乎没有解决方案。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM