void some_func(int param = get_default_param_value());
Run Code Online (Sandbox Code Playgroud)
Dav*_*eas 54
默认参数可以是完整表达式的子集.它必须在编译时和默认参数声明的位置绑定.这意味着它可以是函数调用或静态方法调用,并且它可以采用任意数量的参数,只要它们是常量和/或全局变量或静态类变量,而不是成员属性.
它在编译时和声明函数的位置绑定的事实也意味着如果它使用变量,即使另一个变量在函数调用的位置隐藏原始变量,也将使用该变量.
// 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.
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9827 次 |
最近记录: |