<分区>
为什么 C++ 是这样设计的?...
(这个问题不同,但与
最佳答案
实际上,这并不完全准确。限制是:
7) Local variables shall not be used in a default argument. [ Example:
void f() {
int i;
extern void g(int x = i); //error
// ...
}
—end example ]
8) The keyword
this
shall not be used in a default argument of a member function. [ Example:
class A {
void f(A* p = this) { } // error
};
因此,this
和局部变量不能用作默认值。
例如,以下是有效的:
int a = 1;
int f(int);
int g(int x = f(a)); // default argument: f(::a)
void h() {
a = 2;
{
int a = 3;
g(); // g(f(::a))
}
}
g
将使用值 f(2)
调用,这不是编译时常量。这是直接来自标准的示例。
出现这种情况的原因很常见:要么没有提案,要么被拒绝,认为没有必要或实现起来太困难。
关于c++ - 默认参数必须在编译时绑定(bind) - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12903724/