c++ - 为什么不调用函数的派生类版本?
问题描述
我正在尝试将来自同一基类的多个不同派生类存储在指针向量中。尝试调用其中一个对象的函数会导致分段错误。我没有过多地使用继承,但我已经尝试了我能找到的每个版本,它们要么导致分段错误,要么只是调用基类的函数。
我对 C++ 比较陌生,之前没有发表太多文章,所以如果我共享太多代码、遗漏任何重要内容或在任何其他方面(风格、效率等)搞砸了,请告诉我。
编辑:getPlayer 函数现在不再尝试返回 Random 或 Human,而是返回一个 int,它指示要创建的 Player 类型。新代码仍然会在同一点导致段错误。(排除 getPlayer 因为它只返回一个 int 并且不再是问题的原因。)
这是我定义基类(Player)和派生类(Human 和 Random)的地方:
#include <string>
#include <iostream>
#include <limits>
#include <time.h>
#include "Othello.h"
using namespace std;
// Player interface to choose game moves
class Player {
public:
// Selects and returns a move
virtual int getMove(Othello &game) {
return 0;
}
};
// User-operated player
class Human: public Player {
public:
int getMove(Othello &game) {
int move = 0;
bool valid= false;
while (!valid) {
cout << "Select a move: " << endl;
cout << "-> ";
cin >> move;
if (cin.good()) { valid = true; }
else {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Invalid input. Try again.\n" << endl;
}
}
return move;
}
};
// Basic bot - selects a move at random
class Random: public Player {
public:
int getMove(Othello &game) {
srand(time(NULL));
return ( 1 + rand() % game.n_moves );
}
};
这是导致线路段故障的主要功能move = players[state-1]->getMove(game)
:
int main() {
// Select players (human, AI, random, etc.)
// players[0] is left empty to keep the index consistent with the player id
vector<Player*> players(2);
int type;
for ( int i : {1, 2} ) {
type = getPlayer(i);
if (type == 1) { players.push_back( new Human() ); }
else if (type == 2) { players.push_back( new Random() ); }
}
// Load and start the game
Othello game = loadBoard();
int state = game.getState(1); // 1 or 2 for turn, or 0 for game over
// Continue making moves until the game ends
int move;
int legal;
while(state != 0) {
game.print();
legal = 0;
cout << "PLAYER " << game.turn << endl;
while (legal == 0) {
move = players[state-1]->getMove(game);
legal = game.doMove(move);
}
state = game.getState();
}
game.print();
game.score();
return 1;
}
解决方案
vector<Player*> players(2);
声明一个带有两个元素的向量,这两个元素都将默认初始化为nullptr
.
稍后,您再添加两个元素,这样players
就有 4 个元素。
当state
值为1
or2
时,调用players[state-1]->getMove(game);
将取消引用空指针,从而导致您的分段错误。
您可能希望players
最初定义为空 ( vector<Player*> players;
),并更新此定义前行的注释。(该评论以其当前形式似乎与您稍后访问玩家向量的方式无关。)
推荐阅读
- javascript - 有没有办法防止排他的水平/垂直平移/滚动,即栏杆?
- c# - “System.Web.UI.Page”不包含“DataItem”的定义
- flutter - 如何在颤动中更改文本字段的晦涩字符?
- javascript - Map.get() 在异步函数中返回未定义
- python - 用python编辑文本文件中的字典
- python - Django 2.2.5 的密码重置问题
- python - Python Pandas 使用先例行值更新行中的值
- python - 在 numpy 数组中逐元素应用操作
- reactjs - 反应未将 className 样式应用于按钮
- javascript - Javascript延迟图像更改