gpt4 book ai didi

c++ - 如何在 switch 语句中声明一个全局对象

转载 作者:行者123 更新时间:2023-11-27 22:42:49 26 4
gpt4 key购买 nike

我遇到了一个问题,我需要根据用户输入为类声明一个对象。问题是对象的范围卡在switch语句中,我想知道有没有办法让它公开。

//ask the user to choose the class of the first fighter
cout << "Welcome to the fighting arena! Would you like the first competitor to be a FIGHTER <1>, a WIZARD <2>, a ROGUE <3>, or a RANGER <4>?" << endl;
cin >> competitor1;
cout << "And what is the name of the competitor?" << endl;
cin >> name1;

//creates an object in the appropriate class and initializes it
switch (competitor1)
{

case 1:
{
Fighter Battler1(name1);
break;
}

case 2:
{
Wizard Battler1(name1);
break;
}

case 3:
{
Rogue Battler1(name1);
break;
}
case 4:
{
Ranger Battler1(name1);
break;
}
default:
cout << "Sorry please enter a valid number!" <<endl << endl;
break;
}

cout << Battler1.hp //this is undefined because of the scope

是的,所有内容都写在主要功能中,我知道问题是作用域,只需要一种方法来解决它。

最佳答案

我根本不会在这里使用 switch case,而是使用一组仿函数,每个仿函数创建不同类型的战斗机并返回指向其基础的指针,即

template<typename T>
std::unique_ptr<Champion> Create( ) { return std::make_unique<T>( ); }

std::function<std::unique_ptr<Champion>(void)> createFunctions [] = {
Create<Fighter>
,Create<Rogue>
,Create<Wizard>
,Create<Ranger>
};

用法:

std::cin >> competitor1;
std::unique_ptr<Champion> Battler1 = createFunctions[competitor1];
std::cout << Battler1->hp;

关于c++ - 如何在 switch 语句中声明一个全局对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46983236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com