C++里的static成员变量

 1 #include<iostream>
 2 using namespace std;
 3 
 4 //int g_count = 0;
 5 class Test
 6 {
 7 public:
 8 
 9     Test()
10     {
11         a = 0;
12         count++;
13         cout<<"default constructor "<<count<<endl;
14     }
15     Test(int b)
16     {
17         a = b;
18         count++;
19         cout<<"int constructor "<<count<<endl;
20     }
21     Test(const Test& in)
22     {
23         a= in.a;
24         count++;
25         cout<<"copy constructor "<<count<<endl;
26     }
27     ~Test()
28     {
29         count--;
30         cout<<"destructor "<<count<<endl;
31     }
32 private:
33     int a;
34     static int count;
35 
36 };
37 //int Test::count;
38 Test test_func()
39 {
40     Test tst;
41     return tst;
42 }
43 
44 int main()
45 {
46     Test test1 = test_func();
47     //Test test2(test1);
48 
49     return 0;
50 }

这样的一段代码,如果37行注释掉的话,编译会过不了,g++提示undefined reference to `Test::count',vc2012提示unresolved external symbol "private: static int Test::count"

原本以为class里定义的static变量会自己找一个合适的静态变量区存放,后来想想需要指定一个地方定义也有道理,因为class的定义通常在头文件里面,被很多地方include,不自己找一个地方定义的话就会造成麻烦。

值得注意的是,虽然class里面声明(还是定义)的时候用了static,在外面声明的时候却没有用,估计用了static的话,在其他地方又要出现unresolved external symbol 之类的报错。c++不完善的地方还是蛮多。

上面写错了,其他地方本来就不应该直接用这个static变量,在外面也加上static是应该的

posted on 2013-12-12 20:06  zcranberry  阅读(191)  评论(0编辑  收藏  举报

导航