c++ - 在 C++ 中创建具有随机枚举类型的 Card 对象

标签 c++ enums

我目前正处于学习 C++ 的初级阶段(来自 Java 背景),我很难理解为什么我的程序无法运行。我的程序的目标是能够创建一个 Card 对象,其中随机枚举类型(步兵、骑兵或炮兵)将与该对象相关联。这意味着每次我创建一张新卡片时,这张卡片都会有步兵、骑兵或炮兵的标签。

这是我目前所拥有的:

卡片.h

#include <iostream>
#include <string>

using namespace std;

class Card
{
public:
    enum CardType
    {
        INFANTRY,
        CAVALRY,
        ARTILLERY
    };
    Card();
    Card(CardType type);

    CardType GetType();
    string toString(CardType type);

private:
    CardType type;
};

卡片.cpp

#include "Card.h"
#include <iostream>

using namespace std;

Card::Card() { }

Card::Card(Card::CardType type) // creates a card with a random CardType
{ 
    type = static_cast<Card::CardType>(rand() % 3);
}

Card::CardType Card::GetType() 
{
    return type;
}

string Card::toString(Card::CardType type)
{
    switch (type)
    {
    case Card::CardType::INFANTRY:      return "Infantry";
    case Card::CardType::CAVALRY:       return "Cavalry";
    case Card::CardType::ARTILLERY:     return "Artillery";
    }
}

驱动.cpp

#include <iostream>
#include "Card.h"

using namespace std;

int main()
{
    Card c;

    c.toString(c.GetType());
}

Visual Studio 能够构建我的程序,但在构建后立即卡住,所以我猜我做错了什么。

是否有更简单/更有效的方法来实现我希望我的程序执行的操作?

我还不太了解 C++,所以任何指针都会有所帮助。

感谢您的参与!

最佳答案

问题在于您的对象创建。

因为,在您的卡片类中有两个构造函数,即默认构造函数和参数构造函数,当您使用 Card c; 语句创建对象时,将调用默认构造函数。因此,为了调用参数构造函数,您必须使用 Card c(Card::CardType::INFANTRY);

关于c++ - 在 C++ 中创建具有随机枚举类型的 Card 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33931608/

相关文章:

c++ - google-cloud-cpp CMake 生成失败

java可转换枚举

c++ - 值初始化枚举的行为

swift - 类型 'Self' 不符合协议(protocol) 'Hashable'

c++ - 将 QComboBox 文本写入文件

c++ - 有人可以解释这里发生了什么(类和构造函数/析构函数)吗?

c++ - 在 C/C++ 中创建 10 位数据类型

c++ - c、使用 dec2bin 转换器填充数组

ios - 枚举 : Count and list all cases (from outside! )

java - 为什么不从 Enum<E extends Enum<E>> 扩展