原文链接:https://www.csdn.net/gather_20/NtzaMgxsODQtYmxvZwO0O0OO0O0O.html
C++ Programming language 10.2.4中提到一句话:静态成员,包括函数和数据成员,都必须在某个地方另行定义,“另行”究竟指的是什么意思呢?
如果把包含有static成员的类的定义放在头文件中,而在源文件中调用这个static成员变量将无法通过编译,正确的做法是在相应的源文件中重新定义这个类成员变量
第一种情况:
#include <iostream>
using namespace std;
class C
{
public:
static int x;
static int f ()
{
return x;
}
};
int main ()
{
cout << C::f() << endl;
return 0;
}
报出了main.cc:11: undefined reference to `C::x’的链接期错误,原因是x作为static成员变量没有在类外定义。
第二种情况
#include <iostream>
using namespace std;
class C
{
public:
static int x;
static int f ()
{
return x;
}
};
static int C::x=4;
int main ()
{
cout << C::f() << endl;
return 0;
}
报出了main.cc:15: error: ‘static’ may not be used when defining (as opposed to declaring) a static data member的编译期错误,这又是为什么呢?
第三种情况(编译通过)
#include <iostream>
using namespace std;
class C
{
public:
static int x;
static int f ()
{
return x;
}
};
int C::x=4;
int main ()
{
cout << C::f() << endl;
return 0;
}
这次编译链接通过,程序运转正常,原来2中的问题是在类外定义static变量时要省去static关键字
第四种情况
#include <iostream>
using namespace std;
class C
{
public:
static int x;
static int f ()
{
return x;
}
};
int main ()
{
int C::x=4;
cout << C::f() << endl;
return 0;
}
这一次又报出了main.cc:17: error: invalid use of qualified-name ‘C::x’的错误,原来static变量在编译单元内的定义必须是全局的
总结:
必须在某个地方另行定义,但static成员函数可以在类内定义
static成员变量必须在类外定义,且必须在编译单位内全员定义,不能定义在某个域内,如函数等
static成员(包括变量和函数),在类外重新定义时,必须省略原有的static关键字。