【发布时间】:2020-07-26 13:10:01
【问题描述】:
我正在尝试为基于文本的游戏实现一个角色选择方法,我知道它不会像我那样工作,因为我返回一个对象的引用,该对象的生命周期仅限于方法调用。我还尝试在不引用 Fighter 父类并根据玩家角色选择返回子类(Samus 和 Ryu)的情况下实现该方法,但随后我会收到此错误:无效的抽象返回类型“Fighter”。
Fighter characterSelection(int player,bool checkForBot, Fighter &fig)
{
int input;
string newName;
if(checkForBot)
{
input = (rand()%2)+1;
}
else{
cout << "Please choose your Fighter player"<<player<<": \n1. Samus\n2. Ryu\n";
input = readInput<int>();
}
if(input == 1)
{
Samus sam;
if(checkForBot)
{
cout << "Bot selected Samus!";
}
else{
cout << "Player"<<player<<" selected Samus!\nDo you wish to change your fighters name?\n1.Yes\n2.No\n";
input = readInput<int>();
if(input == 1)
{
cout << "new Name: ";
newName = readInput<string>();
changeName(newName,sam);
}
}
return sam;
}
else if(input == 2)
{
Ryu ry;
if(checkForBot)
{
cout << "Bot selected Ryu!";
}
else {
cout << "Player"<<player<<" selected Ryu!\nDo you wish to change your fighters name?\n1.Yes\n2.No\n";
input = readInput<int>();
if(input == 1)
{
cout << "new Name: ";
newName = readInput<string>();
changeName(newName,ry);
}
}
return ry;
}
}
在选择了一个字符并结束函数调用后,将调用对象的析构函数,从而使引用链接到一个不存在的对象。
int main()
{
int input;
string newName;
bool checkForBot;
int player=1;
while(true)
{
cout << "1. PVP \n2. PVE\n";
input = readInput<int>();
if(input == 1)
{
checkForBot = false;
//Character Selection
Fighter &fig1 = characterSelection(player,checkForBot,fig1);
player++;
Fighter &fig2 = characterSelection(player,checkForBot,fig2);
//Battle
fightPVP(fig1, fig2);
}
else if(input ==2)
{
//Character Selection
Fighter &fig1 = characterSelection(player,checkForBot,fig1);
checkForBot = true;
Fighter &bot = characterSelection(player,checkForBot,bot);
//Battle
fightPVE(fig1, bot);
}
}
return 0;
}
有没有其他方法可以解决这个问题,而不是引用父类,然后在函数调用中创建子类?
【问题讨论】:
-
你从
characterSelection函数返回什么? -
您正在(ab)使用允许引用右值的 MSVC 扩展。函数本身返回一个值,而不是引用。
标签: c++ polymorphism abstraction