[問題] struct使用變數的static問題
開發平台(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
10/19 23:40, 1F
→
10/19 23:40,
8年前
, 2F
10/19 23:40, 2F
→
10/19 23:41,
8年前
, 3F
10/19 23:41, 3F
喔喔 這個我了解
只是覺得直接這樣預設參數的寫法比較簡潔,還可以順便宣告一些變數XD
而且只是想知道到底為什麼會造成現在的這種錯誤
推
10/20 00:02,
8年前
, 4F
10/20 00:02, 4F
推
10/20 00:03,
8年前
, 5F
10/20 00:03, 5F
→
10/20 00:04,
8年前
, 6F
10/20 00:04, 6F
→
10/20 00:05,
8年前
, 7F
10/20 00:05, 7F
推
10/20 00:09,
8年前
, 8F
10/20 00:09, 8F
→
10/20 00:10,
8年前
, 9F
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
10/20 04:54, 10F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章