我正在使用涉及多个类的C ++制作棋盘游戏。当我在piece.h中包含board.h的头文件时,棋盘上的所有成员都可以被识别。但是当我同时将board.h链接到piece.h时,董事会成员未被认可。
这是我如何链接它们:

-在piece.h

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


-在board.h

    #ifndef BOARD_H_
    #define BOARD_H_
    #include<iostream>
    #include "piece.h"


我声明了板的多个块成员和板函数的块类型参数,它们工作正常。但是在需要板参数的块中声明一个void函数,例如:

    void horizontal         (Board b);
    void vertical           (Board b);
    void diagonal           (Board b);


导致出现错误,提示“未声明板”

最佳答案

包含文件基本上告诉预处理器“在此处复制该文件的内容”。如果两个标头互相引用,则您有一个循环引用,该引用不能编译。编译器必须至少了解一些有关所使用的数据类型的信息。
这可以通过使用前向声明来完成:

董事会

class Piece; // Forward declaration without defining the type

class Board
{
    // Board can makes use of Piece, only as long
    // as it does not need to know too much about it.
    // References and pointers are ok.
    Piece* foo();
    void bar(Piece&);
};


片数

#include "Board.h"

class Piece
{
    // Actual definition of class.
    // At this point Board is fully defined and Piece can make use of it.
    Board* foo() { /*...*/ }
    void bar(Board& x) { /*...*/ }

    // Not only references are possible:
    Board baz(const Board x) { /*...*/ }
};


Board.cpp

#include "Board.h"
#include "Piece.h"

// Implementation of Board's functions can go after Piece's definition:
Piece* Board::foo() { /*...*/ }
void Board::bar(Piece& x) { /*...*/ }

关于c++ - 当我将两个头文件链接在一起时,一个无法识别另一个,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31597711/

10-14 23:59
查看更多