为什么成员变量不能用作参数的默认值? [英] Why can member variables not be used as defaults for parameters?

查看:326
本文介绍了为什么成员变量不能用作参数的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

非静态成员作为非静态成员函数的默认参数

如果我错了,更正我,但我认为默认参数的工作方式是:

Correct me if I am wrong, but the way I think default parameters work is this:

函数调用,它开始将参数推入堆栈。当它缺少参数时,它将开始将默认值推入堆栈,直到所有必需的参数被填充(我知道这是一个简化,因为参数实际上是从右向左推,所以它将以默认值开始,但是想法是一样的)。

When the compiler sees the function call, it starts pushing the parameters onto the stack. When it runs out of parameters, it will start pushing the defaults onto the stack until all required parameters are filled (I know this is a simplification, since parameters are actually pushed from right to left, so it will start with the defaults, but the idea is the same).

如果这是真的,为什么不能使用成员变量作为默认值?在我看来,由于编译器正常推送他们在调用站点,它应该能够解决它们很好!

If this is true, why can't member variables be used as defaults? It seems to me that since the compiler is pushing them as usual at the call site, it should be able to resolve them just fine!

EDIT 由于答案似乎我的问题被误解,让我澄清。我知道这是这种情况,我知道语言是什么,是不允许的。我的问题是为什么语言设计者选择不允许这样做,因为它似乎自然工作。

EDIT Since it seems by the answers my question was misunderstood, let me clarify. I know this is the case, and I know what is and isn't allowed by the language. My question is why did the language designers choose to not allow this, since it seems to naturally work.

推荐答案

你要求可以被转换成这个简单的例子

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

这篇关于为什么成员变量不能用作参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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