簡體   English   中英

在 C++ 的結構中聲明 static arrays

[英]Declare static arrays in a struct right in C++

我試圖聲明 static 數組:

#include <iostream>
#include <string.h>
using namespace std;

struct tagData{
  static string tags[];
};

int main(){
  tagData::tags[3];
  tagData::tags[0] = "default";
  tagData::tags[1] = "player";
  tagData::tags[2] = "enemy";
  return 0;
}

但結果發生了錯誤:

*Path*\cczPqyfY.o:main.cpp:(.text+0x1e): undefined reference to `tagData::tags[abi:cxx11]'
*Path*\cczPqyfY.o:main.cpp:(.text+0x32): undefined reference to `tagData::tags[abi:cxx11]'
*Path*\cczPqyfY.o:main.cpp:(.text+0x46): undefined reference to `tagData::tags[abi:cxx11]'
collect2.exe: error: ld returned 1 exit status

我正在尋找一些關於如何在結構中聲明 static arrays 的信息,但不能。 任何人都可以給我一個例子或以另一種方式幫助我嗎?

PS我試圖用GCC 8.1.0版編譯這段代碼;

struct tagData{
      static string tags[];
    };

這個 static class 成員必須在全局 scope中定義,而不是像 ZC1C425268E68394F11 中的main局部變量:

string tagData::tags[3];

現在,一旦手續辦妥,您可以手動訪問其 class 成員, main或任何其他 function:

int main(){
      tagData::tags[0] = "default";
      tagData::tags[1] = "player";
      tagData::tags[2] = "enemy";
      return 0;
    }

但是,如果目標是初始化數組,還有更好的方法。 只需將其初始化為其定義的一部分:

string tagData::tags[3]={"default", "player", "enemy"};

注意:在定義 static class 成員時,您應該始終牢記static 初始化順序失敗

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM