C 中的特殊枚举

Peculiar enum in c++

本文关键字:枚举      更新时间:2023-10-16

在库中,我遇到了一个怪异的结构,该结构用作枚举:

typedef struct SetControl
{
  const static uint16_t RC_MODE_ERROR;
  const static uint16_t RELEASE_CONTROL_SUCCESS;
  const static uint16_t OBTAIN_CONTROL_SUCCESS;
  const static uint16_t OBTAIN_CONTROL_IN_PROGRESS;
  const static uint16_t RELEASE_CONTROL_IN_PROGRESS;
  const static uint16_t RC_NEED_MODE_F;
  const static uint16_t RC_NEED_MODE_P;
  const static uint16_t IOC_OBTAIN_CONTROL_ERROR;
} SetControl;

在任何地方都不会初始化成员,但即使RC_MODE_ERROR等于0,RELEASE_CONTROL_SUCCESS等于1,依此类推。我知道,因为我已经用printf记录了它。到目前为止,我还没有看到类似的东西。为什么它甚至可以工作(我认为默认情况下将通过随机数据初始化值,还是0)?与标准enum相比,是否有任何添加值?

接下来我可以尝试什么?

首先,这是不是枚举,这是一个结构。这些是不同的概念,但我认为您知道,只是对这里的用法感到困惑。

不是期望将结构分配给这些值的成员(例如,枚举会发生)。

我很确定这些成员在您的代码中的某个地方被初始化,或者是宏,因此在某个地方定义了。


搜索github后,它们是初始化的,因此:

const uint16_t DJI::OSDK::ErrorCode::ControlACK::SetControl::RC_MODE_ERROR = 0x0000;
const uint16_t DJI::OSDK::ErrorCode::ControlACK::SetControl::RELEASE_CONTROL_SUCCESS = 0x0001;
const uint16_t DJI::OSDK::ErrorCode::ControlACK::SetControl::OBTAIN_CONTROL_SUCCESS = 0x0002;
const uint16_t DJI::OSDK::ErrorCode::ControlACK::SetControl::OBTAIN_CONTROL_IN_PROGRESS = 0x0003;
const uint16_t DJI::OSDK::ErrorCode::ControlACK::SetControl::RELEASE_CONTROL_IN_PROGRESS = 0x0004;
const uint16_t DJI::OSDK::ErrorCode::ControlACK::SetControl::RC_NEED_MODE_F = 0x0006;
const uint16_t DJI::OSDK::ErrorCode::ControlACK::SetControl::RC_NEED_MODE_P = 0x0005;
const uint16_t DJI::OSDK::ErrorCode::ControlACK::SetControl::IOC_OBTAIN_CONTROL_ERROR = 0x00C9;

在dji_error.cpp中。

需要分别定义静态成员。

ex:

// in example.h
struct SetControl
{
    const static uint16_t RC_MODE_ERROR; // this is only a declaration
};
// in example.cpp
const uint16_t SetControl::RC_MODE_ERROR = 1; // this is the definition