gpt4 book ai didi

C++ 默认函数参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:03:05 26 4
gpt4 key购买 nike

我想实现这个:

- second parameter by default set to first argument

类似于:

int foo (int a, int b = a);

但是怎么做呢?

非常感谢!

最佳答案

这是被禁止的:

8.3.6 默认参数 [dcl.fct.default]

9) Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in default argument expressions, even if they are not evaluated. Parameters of a function declared before a default argument expression are in scope and can hide namespace and class member names. [ Example:

int a;

int f(int a , int b = a); / / error: parameter a

/ / used as default argument

typedef int I;

int g( float I , int b = I (2)); / / error: parameter I found

int h(int a , int b = sizeof (a )); / / error, parameter a used

/ / in default argument

—end example ]

另一种是重载:

int foo(int a, int b);

int foo(int a)
{
return foo(a,a);
}

关于C++ 默认函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12847456/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com