Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么赢了';t我的C++;当我的类有静态成员时的程序链接?_C++_Static - Fatal编程技术网

C++ 为什么赢了';t我的C++;当我的类有静态成员时的程序链接?

C++ 为什么赢了';t我的C++;当我的类有静态成员时的程序链接?,c++,static,C++,Static,我有一个叫做Stuff的小类,我想把东西放进去。这些东西是int类型的列表。在我的代码中,无论我使用什么类,我都希望能够在Stuff类中访问这些东西 Main.cpp: #include "Stuff.h" int main() { Stuff::things.push_back(123); return 0; } h: #include <list> class Stuff { public: static list<int> things

我有一个叫做Stuff的小类,我想把东西放进去。这些东西是int类型的列表。在我的代码中,无论我使用什么类,我都希望能够在Stuff类中访问这些东西

Main.cpp:

#include "Stuff.h"

int main()
{
    Stuff::things.push_back(123);
    return 0;
}
h:

#include <list>

class Stuff
{
public:
    static list<int> things;
};
#包括
课堂材料
{
公众:
静态列出事物;
};
但我在这段代码中遇到了一些构建错误:

错误LNK2001:未解析的外部符号“public:static class std::list Stuff::things”(?things@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++如何处理静态成员。所以请解释一下我这里的错误。

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

#include "Stuff.h"

list<int> Stuff::things;
#包括“Stuff.h”
列出东西;

确保在程序中包括
Stuff.cpp
以及
Main.cpp

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

例如:

class X {
    public:
        static int i;
};
还必须具备以下条件:

int X::i = 0; // definition outside class declaration

Stuff::things只是声明的,但没有定义

请使用:

// Stuff.cpp
#include "Stuff.h"

std::list<int> Stuff::things;
//Stuff.cpp
#包括“Stuff.h”
列出东西;
添加了:保护头文件不被多个包含也是一个很好的做法:

// Stuff.h
#ifndef STUFF_H_
#define STUFF_H_

#include <list>

class Stuff {
    public:
       static std::list<int> things;
};

#endif
//Stuff.h
#ifndef材料_
#定义东西_
#包括
课堂材料{
公众:
静态std::列出事物;
};
#恩迪夫

静态成员必须在类中声明,但必须在其实际所在的单元(cpp文件)中定义


唯一的例外是类是模板:在这种情况下,您必须在类之外定义成员,但也必须在头文件中提供类声明。

只为您的信息,为什么这是C++中的所有全局变量(包括静态全局变量)。是在主函数开始执行之前创建的。

我是否可以建议您尝试格式化代码示例?:-)我会的,如果我知道怎么做的话,尽管我注意到格雷格很好地为梅做了这件事,她准备把我的答案和…两个新答案放在一起。就因为我知道。@Greg-那应该是
list Stuff::things谢谢,刚刚注意到并修复了:)