C++里的static成员变量
2013-12-12 20:06
246 查看
#include<iostream> using namespace std; //int g_count = 0; class Test { public: Test() { a = 0; count++; cout<<"default constructor "<<count<<endl; } Test(int b) { a = b; count++; cout<<"int constructor "<<count<<endl; } Test(const Test& in) { a= in.a; count++; cout<<"copy constructor "<<count<<endl; } ~Test() { count--; cout<<"destructor "<<count<<endl; } private: int a; static int count; }; //int Test::count; Test test_func() { Test tst; return tst; } int main() { Test test1 = test_func(); //Test test2(test1); return 0; }
这样的一段代码,如果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是应该的
相关文章推荐
- effective C++: 8.定制new和delete
- 记录自己学c语言的历程,这是第一篇
- C++设计模式大总结_一个工程方便复习和修改
- c语言课程设计笔记
- 纯C语言写的编译器
- 行列式计算之降阶--C++模板实现
- 自己实现string类的相关函数
- C# 调用C++dll string传递问题
- 浅析GCC下C++类对象的内存布局
- 【C语言学习笔记】之sizeof
- The C++ Standard Library之auto_ptr
- VS2010下生成dll的方法
- C#调用c++的dll报错:“尝试读取或写入受保护的内存。这通常指示其他内存已损坏“
- 二叉树的C++实现
- 纯C语言写的:迷宫游戏
- 纯C语言写的贪吃蛇源码
- C++ DirectUI库收集
- 纯C语言写的拼图游戏源码
- C++中引用(&)的用法和应用实例
- C++ 需要返回值的函数却没有返回值的情况 单例模式