我有以下文件:

H档

class myclass
{
   static int variable;

   // constructor
   myclass();
}

CPP文件
// initialize this variable
int myclass::variable = 0;

myclass::myclass()
{
   // I use here the static variable
}

我的问题是:什么时候初始化静态变量?首先还是之后的构造函数?

如果我把
int myclass::variable = 0;

类构造函数定义后的一行?在实例化类的对象之前,它还会被初始化吗?

最佳答案

这样的静态变量将在应用程序启动时初始化,我认为这将是在实例化“myclass”之前的方式。

基本上,由于这个原因,在哪里定义它都没有关系。

但是,如果您创建“myclass”的全局副本,那么我相信您会遇到问题。将定义放在变量初始化之前是完全合法的,例如

myclass globalInstance;
int myclass::variable = 0;

在以上情况下,我很确定在初始化变量之前将调用myclass的构造函数。在这种情况下,最好在变量之后定义myclass。

编辑:请参阅http://www.parashift.com/c++-faq/static-init-order.html

关于c++ - 静态变量的初始化:与位置有关?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11591221/

10-11 15:11
查看更多