gpt4 book ai didi

c++ - 调用类构造函数导致段错误 (C++)

转载 作者:行者123 更新时间:2023-11-28 00:13:48 24 4
gpt4 key购买 nike

我正在编写棋盘游戏。当我调用游戏的构造函数(带参数)时,程序出现段错误。

主文件:

#include <iostream>
#include "game.h"
using namespace std;

int main(){
int p_count = 2;
Game g(p_count);
//g.play();
}

游戏标题:

#ifndef GAME_H_
#define GAME_H_
#include <iostream>
#include "board.h"
#include "player.h"

using namespace std;

class Game{

private:
Board b;
int moves, gamers;
Player players[10];
bool running;

public:
Game (int p_count);
void setup ();
void play ();
void report_score ();
bool in_mate (Player p);
bool in_check (Player p);
};

游戏构造器:

#include "game.h"

Game::Game(int p_count){
running = true;
moves = 0;
gamers = p_count;
}

板头

#ifndef BOARD_H_
#define BOARD_H_
#include <iostream>

using namespace std;

class Piece;

class Board{

private:
static const int SIZE = 8;
Piece *board[SIZE][SIZE];

public:
Board ();

};


#endif /* BOARD_H_ */

板构造器

#include "board.h"
#include "piece.h"
Board::Board(){
bool b = false;
for (int i=0; i<SIZE; i++){
for(int j=0; j<SIZE;j++){
board[i][j]->set_status(b);
}
}
}

播放器标题

#ifndef PLAYER_H_
#define PLAYER_H_
#include <iostream>
#include "board.h"
#include "piece.h"

using namespace std;

class Player{

private:
static const int NUM = 16;
Piece pieces[NUM];
int side;
public:
Player ();
Player (int p);
#endif

播放器构造函数

#include "player.h"
Player::Player(){
side = 0;
}

片头

#ifndef PIECE_H_
#define PIECE_H_
#include <iostream>
#include "board.h"

using namespace std;

class Board;

struct location{
int row;
int col;
};

class Piece{

private:
location pos_moves[50], loc;
char type;
bool status;
int moved, team;

public:
Piece ();
Piece (int piece_num, int bel);
void set_status (bool b);
};

#endif /* PIECE_H_ */

片段实现

#include "piece.h"
Piece::Piece(){
status = false;
team = 0;
moved = 0;
type = 'A';
}

void Piece::set_status(bool b){
status = b;
}

我从初始化未使用变量的构造函数中调用了一些函数,但无论是否包含它们,程序都会崩溃。

最佳答案

我看到的一个问题是您将 board 定义为指针数组,而不是对象,

  Piece *board[SIZE][SIZE];

然后您继续在 Game::Game() 中使用 board,就像 board 指向有效对象一样。

Board::Board(){
bool b = false;
for (int i=0; i<SIZE; i++){
for(int j=0; j<SIZE;j++){

// Problem.
// board[i][j] has not been initialized
// to point to any valid object.
board[i][j]->set_status(b);
}
}
}

您可以通过使 board 成为一个对象数组来解决这个问题。

  Piece board[SIZE][SIZE];

或者确保在使用数组的每个元素之前为其分配内存。

Board::Board(){
bool b = false;
for (int i=0; i<SIZE; i++){
for(int j=0; j<SIZE;j++){

// Allocate memory for the element
// of the array.
board[i][j] = new Piece;
board[i][j]->set_status(b);
}
}
}

我建议使用对象数组。然后,您就不必担心处理内存分配和释放。如果使用指针数组,请阅读The Rule of Three .

关于c++ - 调用类构造函数导致段错误 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31643813/

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