微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么不调用该函数的派生类版本?

如何解决为什么不调用该函数的派生类版本?

我试图将来自同一基类的多个不同派生类存储在指针向量中。尝试调用这些对象之一的功能会导致分段错误。我没有太多使用继承,但是我已经尝试过找到的每个版本,它们要么导致分段错误,要么仅调用基类的函数

我是C ++的新手,之前没有发布太多内容,所以请让我知道我是否共享太多代码,缺少重要内容或在其他方面(样式,效率等)搞混了

编辑:getPlayer函数现在不再返回随机值或人类值,而只是返回一个int值,该值指示要创建哪种类型的Player。新代码仍会在同一点导致段错误。 (getPlayer排除在外,因为它仅返回一个int值,而不再是导致问题的原因。)

这是我定义基类(播放器)和派生类(人类和随机)的地方:

#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的值为12时,对players[state-1]->getMove(game);的调用将取消引用空指针,从而导致分段错误。

您可能希望将players定义为初始为空(vector<Player*> players;),并在此定义之前的行上更新注释。 (该评论目前的形式似乎与以后如何访问玩家向量毫无意义。)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。