当我的班级有静态成员时,为什么我的C++程序不会链接?

Mr *_*ell 6 c++ static

我有一个名为Stuff的小类,我想把东西存入.这些东西是int类型的列表.在我使用的任何类中的代码中,我希望能够在Stuff类中访问这些内容.

Main.cpp的:

#include "Stuff.h"

int main()
{
    Stuff::things.push_back(123);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Stuff.h:

#include <list>

class Stuff
{
public:
    static list<int> things;
};
Run Code Online (Sandbox Code Playgroud)

但是我用这段代码得到了一些构建错误:

错误LNK2001:未解析的外部符号"public:static class std :: list <int,class std :: allocator <int >> Stuff :: things"(?thing @ Stuff @@ 2V?$ list @ HV?$ allocator @ H @std @@@ std @@ A)Main.obj CSandbox

致命错误LNK1120:1个未解析的外部C:\ Stuff\Projects\CSandbox\Debug\CSandbox.exe CSandbox

我是一名C#家伙,我正在尝试为侧面项目学习C++.我想我不明白C++如何对待静态成员.所以请在这里解释我的错误.

Gre*_*ill 15

在类声明中提到静态成员只是一个声明.您必须为链接器包含一个静态成员定义才能正确挂钩所有内容.通常,您会在Stuff.cpp文件中包含以下内容:

#include "Stuff.h"

list<int> Stuff::things;
Run Code Online (Sandbox Code Playgroud)

请务必Stuff.cpp在您的计划中加入Main.cpp.


Kin*_*cal 7

静态数据成员必须在类声明之外定义,就像方法一样.

例如:

class X {
    public:
        static int i;
};
Run Code Online (Sandbox Code Playgroud)

还必须具备以下条件:

int X::i = 0; // definition outside class declaration
Run Code Online (Sandbox Code Playgroud)