当我的类有静态成员时,为什么我的C ++程序不会链接? [英] Why won't my C++ program link when my class has static members?

查看:117
本文介绍了当我的类有静态成员时,为什么我的C ++程序不会链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为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:


错误LNK2001:未解析的外部符号public:std :: list

error LNK2001: unresolved external symbol "public: static class std::list<int,class std::allocator<int> > 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

fatal error LNK1120: 1 unresolved externals C:\Stuff\Projects\CSandbox\Debug\CSandbox.exe CSandbox

我是一个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 ++程序不会链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆