简体   繁体   中英

Initialize static array in C++

I have these classes:

class FS{
  static char mount(Partition* p)
      {return myImpl->mount(p);}
  /*...*/
  KernelFS* myImpl;
};

class KernelFS{
char mount(Partition* p){
   /*...*/
   while(available[i]) i++;
}
  /*...*/
  static bool available[26];
};

Main program only uses static functions from FS, eg:

void main(){
  Partition* p=/*...*/;
  FS::mount(p);
  /*...*/
}

When FS::mount(p) is called, it calls myImpl->mount(p) (which is a function from KernelFS class). And here's the problem. When it comes to

while(available[i]) i++;

...it breaks! I think the problem is that I haven't initialized the array available[26], and I have no idea how to do that... What else can be the problem? Please help.

Btw, main() never creates FS or KernelFS objects, so I think that there is no use of constructors...

您需要在(确切地)一个cpp文件中定义它:

bool KernelFS::available[] = {0};

The problem is that the array is never allocated any memory. You should add this in the global scope:

bool KernelFS::available[] = {false};

Make sure you do it in one cpp file. Adding it in more than one cpp file will result in duplicate symbol error during linking. Also, you shouldn't do this in a header file. The best approach is to add this in the cpp file with the implementation of the KernelFS class.

Note also that static initialization order across compilation units isn't guaranteed. Hence you shouldn't call KernelFS::mount() from static initialization code in another file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM