Valid expressions for default function arguments

♀尐吖头ヾ 提交于 2020-01-13 09:23:26

问题


What are all the possible types of valid expressions for a default argument in a function or member function?


回答1:


Anything that is correct within context of assignment to a variable of function parameter's type.

Edit
The default arguments during compilation are evaluated in terms of type correctness etc, but they are not calculated and no assignment takes place until run-time. You can specify a constructor of a yet to be defined class as a default argument and it's fine, as long as class is defined at the point of function use... The actual calculation/assignment takes place during function call, not at the point of function declaration/definition.

Example:

#include <iostream>

void foo( int a = std::rand())
{
  std::cout << a << std::endl;
}

int main( void )
{
 foo();

 return( 0 );
}

Program output on ideone.com:

1804289383




回答2:


This is detailed in section 8.3.6 of the C++03 standard. It basically amounts to any expression that doesn't depend on anything in local scope, so any expression which depends on local variables, parameters to a function, or on "this" are excluded.



来源:https://stackoverflow.com/questions/9286801/valid-expressions-for-default-function-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!