您的位置:首页 > 编程语言 > C语言/C++

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是应该的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: