非静态成员作为非静态成员函数的默认参数 [英] Nonstatic member as a default argument of a nonstatic member function
问题描述
struct X
{
X():mem(42){}
void f(int param = mem) //ERROR
{
//do something
}
private:
int mem;
};
任何人都可以给我一个原因,为什么这是非法的C ++?也就是说,我知道这是一个错误,我知道错误的意思,我只是不明白为什么会是非法的!
Can anyone give me just one reason as to why this is illegal in C++?! That is to say, I know that it is an error, I know what the error means, I just can't understand why would this be illegal!
推荐答案
您的代码(简化版):
struct X
{
int mem;
void f(int param = mem); //ERROR
};
您希望将非静态成员数据用作成员函数的参数的默认值。第一个问题是:这个类的特定实例的默认值 mem
属于?
You want to use a non-static member data as default value for a parameter of a member function. The first question which comes to mind is this : which specific instance of the class the default value mem
belongs to?
X x1 = {100}; //mem = 100
X x2 = {200}; //mem = 200
x1.f(); //param is 100 or 200? or something else?
您的答案可能是 100
as <$对 x1
调用 mem = 100
。如果是这样,那么它需要实现 f()
:
Your answer might be 100
as f()
is invoked on the object x1
which has mem = 100
. If so, then it requires the implementation to implement f()
as:
void f(X* this, int param = this->mem);
这又要求在初始化其他参数之前首先初始化第一个参数。但是C ++标准不指定函数参数的任何初始化顺序。因此,这是不允许的。它的原因与C ++ Standard不允许的原因相同:
which in turn requires the first argument to be initialized first before initialization of other argument. But the C++ standard doesn't specify any initialization order of the function arguments. Hence that isn't allowed. Its for the same reason that C++ Standard doesn't allow even this:
int f(int a, int b = a); //§8.3.6/9
事实上,§8.3.6/ 9明确说, / p>
In fact, §8.3.6/9 explicitly says,
在调用函数时,每个
计算默认参数。 函数参数的计算
的顺序是
unspecified 。 因此,函数的参数
不应在
默认参数表达式中使用,即使
未评估。
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.
本节的其余部分是一个有趣的阅读。
And rest of the section is an interesting read.
与默认参数相关的一个有趣的主题(与此主题无关):
An interesting topic related to "default" arguments (not related to this topic though):
- Default argument in the middle of parameter list?
这篇关于非静态成员作为非静态成员函数的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!