在C ++中必须默认的函数参数是常量吗? [英] Must default function parameters be constant in C++?

查看:178
本文介绍了在C ++中必须默认的函数参数是常量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void some_func(int param = get_default_param_value());


推荐答案

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

Default parameter can be a subset of the full set of expressions. It must be bound at compile time and at the place of declaration of the default parameter. This means that it can be a function call or a static method call, and it can take any number of arguments as far as they are constants and/or global variables or static class variables, but not member attributes.

它在编译时和在声明函数的地方绑定的事实也意味着如果它使用一个变量,那个变量将被使用

The fact that it is bound at compile time and in the place where the function is declared also means that if it makes use of a variable, that variable will be used even if a different variable shadows the original at the place of the function call.

// 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();

   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() );

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

这篇关于在C ++中必须默认的函数参数是常量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆