作者ric2k1 (Ric)
看板EE_DSnP
標題Re: [問題] 關於static二三問
時間Tue Nov 17 21:44:36 2009
※ 引述《noblebell (高貴的鈴)》之銘言:
: 我在寫hw3時,關於static有些疑惑,煩請版上同學老師了
: 1、我在.cpp檔裡撰寫funx的body時,都打:
: static bool
: XXXXX::XXXXXX(....){
: ......
: ...
: }
: compiler會complain,好像是不能加上static,請問這是為什麼?
static member function 在 class 裏面定義時就有加 static 了,
表示這個 static 是 class scope 的 linkage.
如果你又在外面加 static, 那表示是 file scope 的 linkage,
這與先前的 declaration 不合.
: 2、同樣是在.cpp裡撰寫funx的body時,雖然有#include <XXXX.h>
: 但好像還是要在.cpp裡,自行再對.h裡的static data member做instantiation
: (我看error很久,最後問了goodword才發現這個問題)
: 可是在.h裡,已經做instantiation的static data member,為什麼還要再一次
: instantiation?不懂、不懂
要在 .cpp 檔案裡頭 instantiate static data member 是因為:
1. static data member 對於這個 class 而言是唯一的, 所以不能被 class 物件
instantiate, 而必須在一個獨立的地方 instantiate.
2. 在 class 裏面的 static data member 只算是 declaration, 否則每 include 一次
這個 class 不就 instantiate 一次? 你可以試試看在 .h file 的 class 外面
instantiate static data member, you will see error message if the .h file
is included in multiple .cpp files.
3. The memory of the static data member should be initialized when the
program starts. That is, when the program is loaded to the memory and
before main() is called. Just like the global variables which are stored
in fixed memory.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.224.41.150
1F:推 noblebell:看懂了,謝謝教授~~ 11/18 17:20
2F:推 noblebell:那麼,假如我在.h檔裡撰寫static funx的body,並使用 11/18 20:50
3F:→ noblebell:static data member,會不會因為在.h檔的static data只 11/18 20:51
4F:→ noblebell:是declaration而error? 我測試好像沒有耶....@@ 11/18 20:52