简体   繁体   中英

Peculiar enum in c++

In a library I have come across a weird construction which serves as enum:

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;

The members are not initialized anywhere but even though, RC_MODE_ERROR equals 0, RELEASE_CONTROL_SUCCESS equals 1 and so on. I know because I have logged it with printf. I havent seen anything like it so far. Why does it even work (I thought values will be initialized by random data by default, or 0)? is there any add value from this over standard enum ? I would appreciate all help.

To begin with, this is not an enum, this is a struct. These are different concepts , but I think you knew, just got confused by the usage here.

It is not expected for the members of a struct to be assigned to these values (as for example would happen with an enum ).

I am fairly sure that these members get initialized somewhere in your code, or they are Macros, thus are defined somewhere.


After searching Github , they are initialized, like this:

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;

in dji_error.cpp .

Static members needs to be separately defined.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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