我不确定,但我的猜测是,因为在一个类成员变量只是声明.它们通过构造函数或其他成员函数初始化.
在实例化对象时会发生这种情况.但是对于静态成员,不需要实例化对象.因此,他们需要在课外进行一次初始化.
编辑:
实际上没有必要初始化静态变量,但有必要在类外定义它们以为它们分配内存.只有在定义之后,才能将它们初始化然后在程序中使用.
因为静态变量需要在某处分配一些存储空间。
让我们以这个为例:
struct Example
{
static int counter;
Example() { counter++; }
};
Run Code Online (Sandbox Code Playgroud)
You can create as many Example instances as you want, but there will only ever be one Example::counter variable. It's basically a global variable in disguise. But where should it live? Back in the early days of C++, Stroustrup decided the solution to this was for you to explicitly choose one translation unit (i.e. .cpp file) and declare it there, just as you would a "real" global variable. So you need to do something like
// Only in one .cpp file
int Example::counter = 0;
Run Code Online (Sandbox Code Playgroud)
(Of course, later on templates were invented, and weak symbols to go with them, which could have solved this awkward mess, but it was too late by then.)
| 归档时间: |
|
| 查看次数: |
4204 次 |
| 最近记录: |