【发布时间】:2018-04-30 22:52:00
【问题描述】:
我是 C++ 新手,我被困在我的程序中。这是一个模仿棋盘游戏“战舰”的程序。我们得到了要编辑的代码,我们被要求做的一件事是让程序提示您要放下哪种船(目前只有一艘船)。
我们被赋予了一个特定的船类(Submarine)来开始,我把它做成了一个Ship父类。我计划为每种船型使用派生类,但 Game 类下的函数具有原始 Submarine 类 (&submarine) 的参数(现在是Ship,所以参数是&Ship)。我试图弄清楚如何动态决定参数的类型,以便我可以使用放置船舶的函数。
有没有办法做到这一点?我们只是学习了父/子类,还没有学习模板,这是我一直看到的常用方法。我也看到很多使用虚函数来解决与我类似的解决方案,但我不太明白这对我的情况有何帮助。
这是我之前谈到的一个函数示例(在 Game 类下):
bool placePiece(Ship& piece) // Ship is parent class -- want it to be derived class (1 of 5 options) depending on which class is being used
{
cout << "What coordinate do you want to place the " << toLower(piece.getName()) << " (length "<<piece.getLength()<<") at?\n";
string coordinate = toLower(requeststring());
cout << "What direction do you want the piece to go? (up, down, left or right)\n";
string direction = toLower(requeststring());
piece.setPiece(rowCharToInt(getFirstChar(coordinate)), getFirstInt(coordinate)-1, getFirstChar(direction));
return isValidPlacement(playerBoard, piece);
}
如果需要更多信息,请告诉我!
谢谢
【问题讨论】:
标签: c++ polymorphism dynamic-binding