简体   繁体   English

C ++类静态结构成员定义

[英]C++ class static struct member definition

I have not found a way to initialize the class member succesfully inside the constructor and I can not figure out why. 我还没有找到一种方法在构造函数中成功初始化类成员,我无法弄清楚原因。

I have a header file: 我有一个头文件:

#pragma once

struct STATE_MOUSE {
  bool moving;
  int left_button;
  int right_button;
  int middle_button;
  bool scroll_up;
  bool scroll_down;
};

class Message {
private:
  static STATE_MOUSE state_mouse;
public:
  Message();
  ~Message();
};

Then I have a source file: 然后我有一个源文件:

#include "message.hpp"

STATE_MOUSE Message::state_mouse = {false, 0, 0, 0, false, false};

Message::Message() {
  //Would like to initialize state_mouse here somehow.
}

Message::~Message() {

}

Now to the issue. 现在问题。 This set up seems to work. 这个设置似乎有效。 However I am used to initialize members inside a constructor and I have not found a way to do that with this static struct member. 但是我习惯于在构造函数中初始化成员,而我还没有找到使用这个静态struct成员的方法。

The following method does not work, could someone explain why? 以下方法不起作用,有人可以解释原因吗?

state_mouse.moving = false;

When you declare a member as static it will belong to the class with only one instance and not to the objects of the class , therefore you cannot initialize it inside the constructor. 当你声明成员为static ,将属于class只有一个实例,而不是对的对象class ,因此你无法初始化它的构造函数中。 The constructor is a special member function which mainly exists to initialize the non static members of a new object. 构造函数是一个特殊的成员函数,主要用于初始化新对象的非static成员。

Note that a static member is shared by all objects of the class and when an object changes it, the change can be seen from all other objects of the same class . 请注意, static成员由class的所有对象共享,并且当对象更改它时,可以从同一class所有其他对象中看到更改。 If this is what do you want to achieve, then the method you shown is good. 如果这是您想要实现的目标,那么您展示的方法就是好的。

Static member variables are not associated with each object of the class. 静态成员变量与类的每个对象都没有关联。 It is shared by all objects. 它由所有对象共享。

If you declare a static variable inside the class then you should define it in the cpp file, otherwise, you can get error undefined reference . 如果在类中声明一个静态变量,那么你应该在cpp文件中定义它,否则,你可以获得错误undefined reference

Note that if the static member variable is of const int type (eg int , bool , char ), you can then declare and initialize the member variable directly inside the class declaration in the header file. 请注意,如果静态成员变量是const int类型(例如intboolchar ),则可以直接在头文件的类声明中声明和初始化成员变量。

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

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