更新时间:2022-12-31 15:15:02
你要求可以被转换成这个简单的例子
The essence of what you are asking can be distilled into this simple example
void foo(int a, int b = a);
这在C ++中是不允许的。 C ++不允许默认参数依赖于其他参数。
This is not allowed in C++. C++ does not allow default arguments to depend on other parameters.
使用类成员作为默认参数只是上面的一种特殊情况,因为类成员通过 this
指针和这个
指针只是每个非静态成员函数的另一个隐藏参数。
Using class members as default arguments is just a particular case of the above, since class members are accessed through this
pointer and this
pointer is just another hidden parameter of each non-static member function.
所以,问题是为什么
void foo(int a, int b = a);
不允许。
一个明显的潜在原因是不允许这样做,因为它会对参数赋值的顺序施加额外的要求。如你所知,在C ++中,函数参数求值的顺序是未指定的 - 编译器可以以任何顺序评估参数。然而,为了支持上述默认参数功能,编译器必须确保 a $ c>在
b
。这感觉像一个过度的要求,这限制了我们习惯在C ++中看到的评价顺序的典型***。
One obvious potential reason to disallow this is that it would impose additional requirements on the order of argument evaluation. As you know, in C++ the order of function argument evaluation is unspecified - the compiler can evaluate arguments in any order. However, in order to support the above default argument functionality the compiler would have to make sure that a
is evaluated before b
. This feels like an excessive requirement, which restricts the typical freedom of evaluation order that we are used to seeing in C++.
注意这里
int a;
void foo(int b = a);
。显然,它没有显示上述的评估问题的顺序。
is allowed in C++. And, obviously, it does not exhibit the aforementioned order of evaluation issue.