【问题标题】:Peculiar enum in c++c ++中的特殊枚举
【发布时间】:2017-09-07 12:21:28
【问题描述】:

在一个库中,我遇到了一个奇怪的构造,它用作枚举:

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 有什么附加价值吗?我将不胜感激。

【问题讨论】:

  • @EdChum 但这并未声明为枚举。这些是结构的成员
  • 这些值必须在某个地方以某种方式定义。继续挖掘!
  • 它们看起来像宏,它们可能是在某处定义的宏,是否有一些 #define ... 在某处
  • 你确定没有不设置这些静态成员的cpp文件吗?除非经过编码,否则您所看到的不应发生。
  • @EdChum 没关系,我想我们有时都会这样做

标签: c++ struct enums initialization


【解决方案1】:

首先,这不是一个枚举,这是一个结构。这些是different concepts,但我想你知道,只是被这里的用法弄糊涂了。

期望将结构的成员分配给这些值(例如,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.

【讨论】:

【解决方案2】:

静态成员需要单独定义。

例如:

// 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

【讨论】:

  • 对于 const 整数不是这样。
  • 是的,对于const static 没有初始化程序
猜你喜欢
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多