C ++: перенос enum в классе - PullRequest
       7

C ++: перенос enum в классе

0 голосов
/ 12 сентября 2018

Я хочу обернуть перечисление в классе, чтобы я мог прикрепить к нему методы. Я также хочу, чтобы sizeof (CommandType) == sizeof (U8). Я провел следующий эксперимент:

class CommandType
{
public:
    enum knownTypes;
    CommandType()             { cmdType = CmdType0; }
    CommandType(knownTypes v) { cmdType = (knownTypes)v; }
    operator const U8()       { return cmdType; }
    bool operator ==(CommandType v2) { return cmdType == v2; }
    int f(int x) { return 22; }
    enum knownTypes : U8 { CmdType0, CmdType1, CmdType2, CmdType3, CmdType4 };
private:
    knownTypes cmdType;
};

int main()
{
    CommandType ct = CommandType::CmdType2; // Preproc: no suitable constructor exists to convert from "CommandType::knowntypes" to "CommandType"
    ct = CommandType::CmdType1; // Preproc: no operator matches these operands; operand types are: CommandType = CommandType::knowntypes
    const CommandType ct1c = CommandType::CmdType3; // Preproc: no suitable constructor exists to convert from "CommandType::knowntypes" to "CommandType"
    CommandType ct2 = ct1c;
    const CommandType ct3c = ct1c;
    int ctf = ct.f(0);
    int szct = sizeof(CommandType);
    if (ct2 == ct) // ok
        while (0);
    if (ct2 == ct1c) // ok
        while (0);
    if (ct3c == ct1c) // Preproc: no operator matches these operands; operand types are: CommandType = CommandType::knowntypes
                      // Compiler: no operator found which takes a left-hand operand of type 'const CommandType'
        while (0);

Я получаю некоторые проблемы с препроцессором и даже ошибку компиляции, как показано в комментариях. Как их решить?

1 Ответ

0 голосов
/ 12 сентября 2018

С несколькими исправлениями я превратил код OP в то, что смог компилировать.

Вот проблемы, которые я решил:

  1. Исправление enum knownTypes как упомянуто StoryTeller.

  2. U8 неизвестно. & Rarr; typedef uint8_t U8;

  3. Исправление operator==():

    bool operator ==(CommandType v2) { return cmdType == v2.cmdType; }

  4. Исправление operator==() константности:

    bool operator ==(CommandType v2) const { return cmdType == v2.cmdType; }

После этого я получил только два предупреждения, которые ИМХО не имеют отношения.

#include <cstdint> // needed for uint8_t

typedef uint8_t U8;

class CommandType
{
public:
    enum knownTypes : U8 { CmdType0, CmdType1, CmdType2, CmdType3, CmdType4 };
    CommandType()             { cmdType = CmdType0; }
    CommandType(knownTypes v) { cmdType = (knownTypes)v; }
    operator const U8()       { return cmdType; }
    bool operator ==(CommandType v2) const { return cmdType == v2.cmdType; }
    int f(int x) { return 22; }
private:
    knownTypes cmdType;
};

int main()
{
    CommandType ct = CommandType::CmdType2; // ??? Preproc: no suitable constructor exists to convert from "CommandType::knowntypes" to "CommandType"
    ct = CommandType::CmdType1; // ??? Preproc: no operator matches these operands; operand types are: CommandType = CommandType::knowntypes
    const CommandType ct1c = CommandType::CmdType3; // ??? Preproc: no suitable constructor exists to convert from "CommandType::knowntypes" to "CommandType"
    CommandType ct2 = ct1c;
    const CommandType ct3c = ct1c;
    int ctf = ct.f(0);
    int szct = sizeof(CommandType);
    if (ct2 == ct) // ok
        while (0);
    if (ct2 == ct1c) // ok
        while (0);
    if (ct3c == ct1c) // !!! Preproc: no operator matches these operands; operand types are: CommandType = CommandType::knowntypes
                      // Compiler: no operator found which takes a left-hand operand of type 'const CommandType'
        while (0);
    return 0;
}

Live демо на coliru

Я отметил проблемы ОП с

  • ??? который я не исправил явно (но может быть неявно)
  • !!!, которые решаются с помощью вышеуказанных исправлений.

Примечание:

Когда я определяю operator==(), тогда я определяю и operator!=() (так как мне нравится симметрия). Это можно легко сделать исходя из существующих:

bool operator!=(CommandType v2) const { return !operator==(v2); }

Это до сих пор удобно для обслуживания, так как исправления в operator==() будут охватывать operator!=() также "автоматически".

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...