“static this()”是什么意思?类外是什么意思?
我非常了解静态构造函数,但是在类之外使用 static this()
意味着什么?
import std.stdio;
static this(){
int x = 0;
}
int main(){
writeln(x); // error
return 0;
}
如何访问 static this()
中定义的变量?
I'm very well aware of static constructors, but what does it mean to have a static this()
outside of a class?
import std.stdio;
static this(){
int x = 0;
}
int main(){
writeln(x); // error
return 0;
}
And how do I access the variables define in static this()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它是一个模块构造函数。该代码为每个线程(包括主线程)运行一次。
还有模块析构函数以及共享模块构造函数和析构函数:
这些函数的目的基本上是初始化和取消初始化全局变量。
It's a module constructor. That code is run once for each thread (including the main thread).
There are also module destructors as well as shared module constructors and destructors:
The purpose of these is basically to initialise and deinitialise global variables.
这是模块构造函数。您可以在这里阅读有关它们的信息:http://www.digitalmars.com/d/2.0/ module.html
显然,您无法访问示例中的
x
,因为它是模块构造函数的局部变量,就像您无法使用类构造函数的局部变量来完成它一样。但是您可以在那里访问模块范围全局变量(并初始化它们,这就是模块构造函数的用途)。This is the module constructor. You can read about them here: http://www.digitalmars.com/d/2.0/module.html
Obviously, you can't access
x
in your sample, because it's a module constructor's local variable, just as well as you couldn't have done it with a class constructor's one. But you can access module-scope globals there (and initialise them, which is what the module constructors are for).