将enum作为参数传递给构造函数



当我想将enum值传递给默认构造函数时,我遇到了一个问题。我的枚举是这样定义的:

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) {}

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

编辑:我已经尝试把枚举是一个类也是一个公共成员,并从它派生芯片类,但没有任何成功。

编辑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;
}

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

chips m_doubloon(DOUBLOON);

实际上是一个类成员声明。类成员不能用()初始化,只能用={}初始化。假设您的编译器支持类内初始化(在c++ 11中引入),您应该可以使用

chips m_doubloon{DOUBLOON};
                ^        ^

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

player类中,您应该替换

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

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

您需要将DOUBLOON传递为ENUMchipType::DOUBLOON

相关内容

  • 没有找到相关文章

最新更新