靜態(tài)變量為什么定義在類外面

1、背景

遇上了變量未定義的問題,如下:

 1 #include <iostream>
  2 #include <string.h>
  3 using namespace std;
  4 
  5 
  6 class sample
  7 {
  8 private:
  9 static int s_s1;
 10 int m_s2;
 11 
 12 public:
 13 sample(){ m_s2 = 0; cout << "default constructor! "<< endl;}
 14 sample(sample & s){ cout <<"copy constructor! " << endl;}
 15 void show(void);
 16 };
 17 
 18 void sample::show(void)
 19 {
 20     s_s1++;
 21     m_s2++;
 22     cout << s_s1 << endl;
 23     cout << m_s2 << endl;
 24 }   
 25 
 26 int main(void)
 27 {
 28 sample e1;
 29 e1.show();
 30 sample e2;
 31 e2.show();
 32 
 33 }
 34 
~                                                                                                                                                                                              
~      
root@mkx:~/learn/staticInClass# g++ staticInClass.cpp -o staticInClass
/tmp/ccK5xzjv.o:在函數(shù)‘sample::show()’中:
staticInClass.cpp:(.text+0xe):對(duì)‘sample::s_s1’未定義的引用
staticInClass.cpp:(.text+0x17):對(duì)‘sample::s_s1’未定義的引用
staticInClass.cpp:(.text+0x2c):對(duì)‘sample::s_s1’未定義的引用
collect2: error: ld returned 1 exit status
root@mkx:~/learn/staticInClass#                                  

2、實(shí)例

改成如下,問題就解決了:

 1 #include <iostream>
  2 #include <string.h>
  3 using namespace std;
  4 
  5 
  6 class sample
  7 {
  8 private:
  9 static int s_s1;
 10 int m_s2;
 11 
 12 public:
 13 sample(){ m_s2 = 0; cout << "default constructor! "<< endl;}
 14 sample(sample & s){ cout <<"copy constructor! " << endl;}
 15 void show(void);
 16 };
 17 int sample::s_s1 = 0;
 18 
 19 void sample::show(void)
 20 {   
 21     s_s1++;
 22     m_s2++; 
 23     cout << s_s1 << endl;
 24     cout << m_s2 << endl;
 25 }
 26 
 27 int main(void)
 28 {
 29 sample e1;
 30 e1.show();
 31 sample e2;
 32 e2.show();
 33 
 34 }
 35 
~                                                                                                                                                                                              
"staticInClass.cpp" 35L, 455C 已寫入                   

root@mkx:~/learn/staticInClass# g++ staticInClass.cpp -o staticInClass
root@mkx:~/learn/staticInClass# ./staticInClass 
default constructor! 
1
1
default constructor! 
2
1
root@mkx:~/learn/staticInClass# 

3、總結(jié)

C++ 的靜態(tài)成員變量為什么一定要在類外定義
函數(shù)如下,在C++中聲明靜態(tài)成員變量的時(shí)候,在類中只是進(jìn)行了聲明,并沒有實(shí)際的申請(qǐng)出指針的內(nèi)存,真正的內(nèi)存是定義初始化的時(shí)候才會(huì)進(jìn)行內(nèi)存的申請(qǐng)
為什么這樣呢?
因?yàn)閟tatic類型的變量都是隨著類的,因此不能隨著對(duì)象的創(chuàng)建而申請(qǐng)內(nèi)存,所以需要單獨(dú)的進(jìn)行類外定義,在定義的時(shí)候C++編譯器會(huì)申請(qǐng)內(nèi)存給靜態(tài)指針。
如圖所示:


image.png

其是不屬于對(duì)象的,所以不能隨著對(duì)象創(chuàng)建,所以只能在類外進(jìn)行定義。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容