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:在函数‘sample::show()’中:
staticInClass.cpp:(.text+0xe):对‘sample::s_s1’未定义的引用
staticInClass.cpp:(.text+0x17):对‘sample::s_s1’未定义的引用
staticInClass.cpp:(.text+0x2c):对‘sample::s_s1’未定义的引用
collect2: error: ld returned 1 exit status
root@mkx:~/learn/staticInClass#
2、实例
改成如下,问题就解决了:
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、总结
C++ 的静态成员变量为什么一定要在类外定义
函数如下,在C++中声明静态成员变量的时候,在类中只是进行了声明,并没有实际的申请出指针的内存,真正的内存是定义初始化的时候才会进行内存的申请
为什么这样呢?
因为static类型的变量都是随着类的,因此不能随着对象的创建而申请内存,所以需要单独的进行类外定义,在定义的时候C++编译器会申请内存给静态指针。
如图所示:
其是不属于对象的,所以不能随着对象创建,所以只能在类外进行定义。