问题描述
我有一个名为Stuff的类,我想存储的东西。这些东西是int类型的列表。在我的代码中,无论我使用什么类,我想要能够访问这些东西在Stuff类中。
I have a little class called Stuff that I want to store things in. These things are a list of type int. Throughout my code in whatever classes I use I want to be able to access these things inside the Stuff class.
Main.cpp:
#include "Stuff.h"
int main()
{
Stuff::things.push_back(123);
return 0;
}
Stuff.h:
#include <list>
class Stuff
{
public:
static list<int> things;
};
但我使用此代码遇到一些生成错误:
but I get some build errors with this code:
致命错误LNK1120:1未解决的外部C: \Stuff\Projects\CSandbox\Debug\CSandbox.exe CSandbox
fatal error LNK1120: 1 unresolved externals C:\Stuff\Projects\CSandbox\Debug\CSandbox.exeCSandbox
我是一个C#人,我试图学习C ++的一个副项目。我想我不明白C ++如何处理静态成员。
I am a C# guy, and I am trying to learn C++ for a side project. I think that I don't understand how C++ treats static members. So please explain what I have got wrong here.
推荐答案
在类声明中提到一个静态成员是一个声明
Mentioning a static member in a class declaration is a declaration only. You must include one definition of the static member for the linker to hook everything up properly. Normally you would include something like the following in a Stuff.cpp
file:
#include "Stuff.h"
list<int> Stuff::things;
一定要包括 Stuff.cpp
您的程序以及 Main.cpp
。
Be sure to include Stuff.cpp
in your program along with Main.cpp
.
这篇关于当我的类有静态成员时,为什么我的C ++程序不会链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!