作者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