expected class-name before '{' token
I'm getting the error "expected class-name before '{' token" in my C++ Qt project. After googling it, it seems like its a problem of circular includes.开发者_如何学Go I have pawn.h that includes piece.h, which includes board.h, which completes the circle by including pawn.h. I've read that this can be fixed with forward declarations, but I've tried forward declaring a few of problem classes, and it doesn't work.
#ifndef PAWN_H
#define PAWN_H
#include "piece.h"
class Pawn : public Piece
{
Q_OBJECT
public:
explicit Pawn(QWidget *parent = 0);
};
#endif // PAWN_H
.
#ifndef PIECE_H
#define PIECE_H
#include <QWidget>
#include "board.h"
class Board;
class Piece : public QWidget
{
Q_OBJECT
public:
explicit Piece(QWidget *parent = 0);
void setPosition(int rank, int file);
QPixmap pixmap;
protected:
void paintEvent(QPaintEvent *);
private:
int rank;
int file;
int x;
int y;
};
#endif // PIECE_H
.
#ifndef BOARD_H
#define BOARD_H
#include <QWidget>
#include <QVector>
#include <QGridLayout>
#include "square.h"
#include "pawn.h"
#include "knight.h"
#include "bishop.h"
#include "queen.h"
#include "king.h"
class Board : public QWidget
{
public:
explicit Board(QWidget *parent = 0);
QVector < QVector<Square *> > sqrVector;
Pawn *pawn[8];
Knight *knight[2];
Bishop *bishop[2];
Queen *queen;
King *king;
private:
QGridLayout *layout;
};
#endif // BOARD_H
Instead of randomly trying things, try changing board.h
to include forward declarations for all the pieces:
board.h
class Pawn;
class Knight;
class Bishop;
class Queen;
class King;
And remove the corresponding #include
statements. (You'll probably need to put those #include
statements in board.cpp
, when you decide you need to see inside the various piece classes.)
Your main problem lays in the file: piece.h
. Since board
is not referenced explicitly in the file whatsoever, the include
for it and the forward declaration should be removed. That will break the circle. Additionally, as Greg pointed out, only forward declarations are needed in board.h
.
精彩评论