[問題] 關於static用法

看板C_and_CPP (C/C++)作者 (晃晃)時間11年前 (2014/11/28 18:38), 編輯推噓0(003)
留言3則, 2人參與, 最新討論串1/2 (看更多)
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 大家好 我是剛學C++的新手 剛學到class的部分 剛在寫作業時遇到一個問題一直找不出問題在哪 就是我在class的header file裡面定義了一個 private : static string suitDict[4] ; 然後在class的constructor裡面寫 suitDict[0] = "spade"; suitDict[1] = "heart"; suitDict[2] = "diamond"; suitDict[3] = "club"; 然後complie時就出現錯誤訊息 錯誤訊息 : 錯誤 2 error LNK2001: 無法解析的外部符號 "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > * Card::faceDict" 但是若我把header file裡面的"static"拿到 就可以順利執行 想請問static這樣用的問題在哪裡? 謝謝 相關程式碼長這樣 ---Card.h--- #ifndef CARD_H #define CARD_H #include <string> using namespace std; class Card { public: Card(int, int); string toString(); private: static string suitDict[4]; static string faceDict[13]; int face; int suit; }; #endif --Card.cpp--- #include<iostream> #include"Card.h" using namespace std; Card::Card(int s, int f){ suit = s-1; face = f-1; suitDict[0] = "spade"; suitDict[1] = "heart"; suitDict[2] = "diamond"; suitDict[3] = "club"; faceDict[0] = "A"; faceDict[1] = "2"; faceDict[2] = "3"; faceDict[3] = "4"; faceDict[4] = "5"; faceDict[5] = "6"; faceDict[6] = "7"; faceDict[7] = "8"; faceDict[8] = "9"; faceDict[9] = "10"; faceDict[10] = "J"; faceDict[11] = "Q"; faceDict[12] = "K"; } string Card::toString(){ string s = suitDict[suit] + " of " + faceDict[face] ; return s; } 因為看了書還是不懂問題在哪 因此上來請問大家 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.230.134.90 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1417171100.A.66B.html

11/28 18:56, , 1F
宣告成static之後就不能再建構子裏面宣告
11/28 18:56, 1F

11/28 18:58, , 2F
google c++ class static 找static variable的部份
11/28 18:58, 2F

11/29 00:14, , 3F
要在外部定義靜態類別成員
11/29 00:14, 3F
文章代碼(AID): #1KU52SPh (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1KU52SPh (C_and_CPP)