看板 EE_DSnP 關於我們 聯絡資訊
#include<iostream> #include<iomanip> using namespace std; class A { public: static const int i=100; }; int main() { A a; cout<<sizeof(a)<<endl; system("pause"); return 0; } 你猜執行會看到啥? 4嗎 結果出現了1 超神奇= = 當然把static const去掉之後 就很正常的顯示出4了 how is it possible -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.241.177
Knossos:static const不能算是a這個物件的datamember,它是共用的 12/08 20:32
Knossos:所以a的size不會把它算進去 12/08 20:33
Knossos:以上是我的想法..僅供參考.. 12/08 20:33
lionel20002:如果class裡是空的用sizeof也會變成1 12/08 22:26
lionel20002:推論static const沒有被算到datamember裡 12/08 22:27
ric2k1:Yes, static data member 不屬於任何 class object 12/08 23:34
ric2k1:It acts as a class-scope global variable, shared by 12/08 23:35
ric2k1:all the class onbjects. It can be accessed even without 12/08 23:36
ric2k1:a class object. 12/08 23:36
ric2k1:In addition, sizeof can NEVER return 0... 12/08 23:36
ric2k1:even for empty class.. 12/08 23:37