[問題] struct使用變數的static問題

看板C_and_CPP (C/C++)作者 (edison)時間8年前 (2017/10/19 22:59), 8年前編輯推噓3(307)
留言10則, 4人參與, 8年前最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) G++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 沒有 問題(Question): 最近在練演算法的程式的時候產生了如下的Code(是舉例 所以內容很無意義XD) http://codepad.org/uBfv4QYa struct Foo{ int var; int func(int n=var,int m=var+5){ return n*m; } int init(int n){ var=n; } } meow; int main(){ meow.init(7122); int n; cin>>n; cout<<meow.func()<<endl; } 結果出現了編譯錯誤: sample.cpp:6:20: error: invalid use of non-static data member 'Foo::var' int func(int n=var,int m=var+5){ ^ 依照錯誤內容把var改成static之後 http://codepad.org/ljKfx6Fj struct Foo{ static int var; int func(int n=var,int m=var+5){ return n*m; } int init(int n){ int var=n; } } meow; int main(){ meow.init(7122); int n; cin>>n; cout<<meow.func()<<endl; } 卻出現了這樣子的東西 /tmp/ccwE5wAc.o: In function `main': sample.cpp:(.text.startup+0x15): undefined reference to `Foo::var' collect2: error: ld returned 1 exit status 請問該怎麼修正? 感謝各位大大m(_ _)m 餵入的資料(Input): g++ -std=c++0x -Wextra -O2 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 27.105.249.207 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1508425188.A.10C.html ※ 編輯: edisonhello (27.105.249.207), 10/19/2017 23:05:58

10/19 23:40, 8年前 , 1F
你應該先了解static member的語意是什麼
10/19 23:40, 1F

10/19 23:40, 8年前 , 2F
另外第一段code你想要的功能可以用function overload達成
10/19 23:40, 2F

10/19 23:41, 8年前 , 3F
int func() { return func(var, var + 5); }
10/19 23:41, 3F
喔喔 這個我了解 只是覺得直接這樣預設參數的寫法比較簡潔,還可以順便宣告一些變數XD 而且只是想知道到底為什麼會造成現在的這種錯誤

10/20 00:02, 8年前 , 4F
不看你給的畫面還沒發現,你要初始化var這個變數的話,
10/20 00:02, 4F

10/20 00:03, 8年前 , 5F

10/20 00:04, 8年前 , 6F
就不要再init()裡面又宣告一次"int var"了~ 而且一般用
10/20 00:04, 6F

10/20 00:05, 8年前 , 7F
建構式初始化參數比較好
10/20 00:05, 7F

10/20 00:09, 8年前 , 8F
func的參數是由var決定的話,就不要給參數了~
10/20 00:09, 8F

10/20 00:10, 8年前 , 9F
int func() { int n=var, m = var+5; return n*m; }
10/20 00:10, 9F
因為我以為static的用法 在使用的時候要宣告一次 剛剛測試了一下不加的話 undefined reference 的 error 又多出現了一次 另外會用到 init 只是因為在最後實作我要的東西時可能會重複使用到 所以會寫個 reset 跟 init 來代替建構子的功用 ※ 編輯: edisonhello (27.105.249.207), 10/20/2017 00:30:17

10/20 04:54, 8年前 , 10F
int Foo::var = 0;
10/20 04:54, 10F
文章代碼(AID): #1PwBta4C (C_and_CPP)
文章代碼(AID): #1PwBta4C (C_and_CPP)