保存类指针对象值的变量

Variable that holds value of class pointer object?

本文关键字:变量 对象 指针 保存      更新时间:2023-10-16

我正在尝试创建一个变量来保存类指针对象。

下面是我的两个具有构造函数值的类指针对象。

Goblin *g = new Goblin(6, 6, 3, 8, 2,1);
Barbarian *b = new Barbarian(6, 6, 0, 12, 2, 2);

我想创建一个变量来保存这样的数据,这样我就可以让玩家选择他想成为的生物,这个变量会保存这些数据,所以我可以将其用于我的功能。

这是我要使用的函数的标题。

void battle(Creature *a, Creature *d, std::string nameA, std::string nameD);

这是在main()中调用的函数

battle(g, b, playerName, opponentCreature);

值g和b是我想要用新变量替换的值。我尝试过使用字符串和int变量类型,但没有成功。有人知道我该怎么做吗?

我通过使用这两行让它开始工作。

Creature *personCode = 0;
Creature *opponentCode = 0;

以下是它们与我的程序的联系方式。

std::cout << "Choose your creature." << std::endl;
std::cout << "n1). Goblin." << std::endl;
std::cout << "2). Barbarian." << std::endl;
std::cin >> choice;
std::cin.clear();//clear the input
std::cin.ignore(100, 'n');//ignore 100 char or up to new line.
switch (choice)
{
    case 1:// std::cout << "Goblin" << std::endl;
        playerCreature = "Goblin";
        personCode = new Goblin(6, 6, 3, 8, 2, 1);
        break;
    case 2:// std::cout << "Barbarian" << std::endl;
        playerCreature = "Barbarian";
        personCode = new Barbarian(6, 6, 0, 12, 2, 2);
        break;
}
std::cout << "Choose your opponent" << std::endl;
std::cout << "n1). Goblin." << std::endl;
std::cout << "2). Barbarian." << std::endl;
std::cin >> choice;
std::cin.clear();//clear the input
std::cin.ignore(100, 'n');//ignore 100 char or up to new line.
switch (choice)
{
case 1: //std::cout << "Goblin" << std::endl;
    opponentCreature = "Goblin";
    opponentCode = new Goblin(6, 6, 3, 8, 2, 1);
    break;
case 2: //std::cout << "Barbarian" << std::endl;
    opponentCreature = "Barbarian";
    opponentCode = new Barbarian(6, 6, 0, 12, 2, 2);
    break;
}

这是现在调用的函数。

battle(personCode, opponentCode, playerName, opponentCreature);