我有一个抽象类(其中包含纯虚函数),我使用多态,因此它包含继承该类的类的地址。父母'被称为Piece
,包含指向它的指针的类是Square
。无论如何,我得到一个奇怪的例外,使用以下代码:
标题文件:
#pragma once //Square.h
class Piece; //as I cannot include piece.h, if i do, I actually include myself, because piece.h includes board.h and board.h includes me.
class Square
{
public:
Square(void);
Piece* getPiece();
void setPiece(Piece* piece);
~Square(void);
private:
Piece* _piece;
};
还有第二个:
#pragma once
#include "Square.h"
class Board
{
public:
Board(void);
Square& getSquare(int row, int col);
~Board(void);
private:
Square** _square;
};
最后三分之一:
#pragma once
#include <iostream>
#include "Coord.h"
#include "Board.h"
using namespace std;
class Piece //irellevant variables though, for this question
{
public:
Piece(Coord pos, bool color);
virtual bool isLegalMove(Coord c, Board* b) const = 0;
virtual char getPieceChar() const = 0;
~Piece(void);
protected:
Coord _pos;
bool _color;
};
以及我遇到崩溃的代码本身就是Square getPiece()
函数(当我从main调用它时):
Piece* Square::getPiece()
{
return this->_piece;
}
我知道在那个方格中,_piece
Piece指针为空,但程序崩溃了。
我在使用VS 2012 Ultimate的Windows上,这是Exception消息:
Access violation reading location 0x000000C4.
它说的是关于this->_piece
(当我查看底部变量时),&#39;无法读取内存&#39;,但是当指针为NULL时会出现这种情况。
知道发生了什么事,让我的程序崩溃了吗?