简体   繁体   English

使用静态成员变量

[英]Using a static member variable

Hello in my class Bullet I declare active as false when the bullet isn't active and true when it is. 您好,在我的class Bullet ,当bullet不活动时,我将active声明为false,在bullet不活动时则声明为true。 In my other class that isn't connected to my Bullet class in any way I want to use the bool member active and change it, how can I do that? 在我没有以任何方式连接到Bullet class其他class ,我想使用bool成员active并对其进行更改,我该怎么做?

Im getting the error 我收到错误

Error 18 error LNK2001: unresolved external symbol "public: static bool Bullet::active" (?active@Bullet@@2_NA) C:\\Skolarbete\\Programmering i C++\\ProjectTemplate\\ProjectTemplate\\Alienrow.obj ProjectTemplate

Declaration: static bool active; 宣言: static bool active;

When I use it: Bullet::active = false; 当我使用它时: Bullet::active = false;

Im quite new too C++ so don't hate! 我也是C++新手,所以不要讨厌! Appreciate all the help I can get :D 感谢所有我能得到的帮助:D

A static variable inside a class is actually an external declaration. 类内部的静态变量实际上是一个外部声明。 You still need the variable definition. 您仍然需要变量定义。 This is similar to C external variables. 这类似于C外部变量。

So in the .h file: 因此,在.h文件中:

class Bullet
{
public:
    static bool active;
};

and in the .cpp file, at global scope: 并在.cpp文件中,在全球范围内:

bool Bullet::active = false;

The lack of the variable definition (not declaration) is deduced because your error message actually comes from the linker, not the compiler. 推断出缺少变量定义 (不是声明)是因为您的错误消息实际上来自链接器,而不是编译器。

You forgot to specify the type of the variable (that is to define the object). 您忘记指定变量的类型(即定义对象)。 Write

bool Bullet::active = false;

instead of 代替

Bullet::active = false;

That is at first you have to define the object and only after that you can assign it. 也就是说,首先必须定义对象,然后才可以分配它。

As for the statement you showed 至于你显示的声明

Bullet::active = false;

then it is not a definition of active. 那么它不是活动的定义。 It is an assignment statement. 这是一个赋值语句。

Take into account that the definition should be placed in some module. 考虑到该定义应放在某个模块中。 If you will place it in the header you can get an error that the object is already defined. 如果将其放置在标题中,则会收到错误消息,表明该对象已定义。

static class members need to be defined somewhere, in your case there must be a 静态类成员需要在某个地方定义,在您的情况下,必须有一个

bool Bullet::active;

definition in a cpp file of your choice (a file which #includes the class declaration). 您选择的cpp文件中的定义(一个包含类声明的文件)。
You can think of static members as global variables which happen to be in the "namespace" of the class. 您可以将静态成员视为恰好在类的“名称空间”中的全局​​变量。 The class declaration as such doesn't create any objects, not even the static members, it's just, well, a declaration. 这样的类声明不会创建任何对象,甚至不会创建静态成员,它只是一个声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM