将枚举作为参数传递给构造函数

时间:2015-05-25 11:58:42

标签: c++ oop enums

当我想将枚举值传递给默认的construtor时,我遇到了问题。我的枚举定义如下:

typedef enum
{
    DOUBLOON,
    VICTORYPOINT
} ENUMchipType;

它们存储在单独的.h文件中。

但是当我尝试这样做时:

chips m_doubloon(DOUBLOON);

我收到以下错误:

error: C2061: syntax error : identifier 'DOUBLOON'

默认构造函数的代码是:

chips::chips(
    ENUMchipType chipType = DOUBLOON,
    int amountValue1 = 0,
    int amountValue5 = 0,
    QObject *parent = 0) :
    m_chipType(chipType),
    m_chipCountValue1(amountValue1),
    m_chipCountValue5(amountValue5),
    QObject(parent) {}

有人知道这段代码有什么问题吗?提前谢谢!

编辑:我已经尝试过把enum作为一个类公共成员并从中派生出芯片类,但没有任何成功。

编辑2:这段代码重现了Visual Studio 2013中的错误

#include <string>

using namespace std;

//enums.h
typedef enum
{
    DOUBLOON,
    VICTORYPOINT
} ENUMchipType;

typedef enum
{
    PLAYER1,
    PLAYER2,
    PLAYER3,
    PLAYER4,
    PLAYER5
} ENUMplayer;

// In chips.h
class chips
{
private:
    int m_chipCountValue5;
    int m_chipCountValue1;
    ENUMchipType m_chipType;

public:
    explicit chips(
        ENUMchipType chipType = ENUMchipType::DOUBLOON,
        int amountValue1 = 0,
        int amountValue5 = 0);

    ENUMchipType getChipType() const { return m_chipType; }
};

// Chips.cpp
chips::chips(ENUMchipType chipType, int amountValue1, int amountValue5) :
m_chipType(chipType),
m_chipCountValue1(amountValue1),
m_chipCountValue5(amountValue5) {}

// PLayer.h
class player
{
private:
    ENUMplayer m_ID;
    string m_name;

public:
    chips m_doubloon(DOUBLOON);
    chips m_victoryPoints(VICTORYPOINT);

    explicit player(ENUMplayer ID = PLAYER1, string name = "");

    void setName(string name = "") { m_name = name; }
    void setID(ENUMplayer ID) { m_ID = ID; }

    string getName() const { return m_name; }
    ENUMplayer getID() const { return m_ID; }

};

//player.cpp
player::player(ENUMplayer ID, string name) :
m_ID(ID),
m_name(name) {}

int main() {

    return 0;
}

3 个答案:

答案 0 :(得分:2)

在课程player中,您应该替换

chips m_doubloon(DOUBLOON);
chips m_victoryPoints(VICTORYPOINT);

通过

chips m_doubloon{DOUBLOON};
chips m_victoryPoints{VICTORYPOINT};

答案 1 :(得分:2)

现在你终于发布了足够多的代码,我们看到了这个

chips m_doubloon(DOUBLOON);

实际上是一个类成员声明。无法使用()初始化类成员,只能使用={}。假设您的编译器支持类内初始化(在C ++ 11中引入),那么

就可以了
chips m_doubloon{DOUBLOON};
                ^        ^

或者,您可以在构造函数的初始化列表中初始化成员,而不是在其声明中初始化。

答案 2 :(得分:-1)

您需要将DOUBLOON作为ENUMchipType::DOUBLOON

传递