当我将两个头文件链接在一起时,其中一个无法识别另一个

When I link two header files together, one does not recognize the other

本文关键字:一个 另一个 识别 链接 两个 在一起 文件      更新时间:2023-10-16

我正在使用c++制作一款包含多个类的桌面游戏。当我在board.h中包含piece.h的头文件时,所有的piece成员都被董事会认可。但是,当我同时将board.hpiece.h联系起来时,董事会成员没有被识别。下面是我链接它们的方式:

-In piece.h

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

-In board.h

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

我声明了多个棋盘成员和棋盘函数的棋子类型参数,它们工作得很好。然而,在piece中声明一个接受board参数的void函数,如下所示:

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

导致错误提示"Board has not declared"

包含一个文件基本上告诉预处理器"复制该文件的内容在这里"。如果两个头文件相互引用,则有一个无法编译的循环引用。编译器至少要知道一点使用的数据类型。
这可以通过使用前向声明:

来实现。

Board.h

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&);
};

Piece.h

#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) { /*...*/ }

这个包含方案有两个备选视图。当包含piece.h时,所有的board.h都包含在piece.h主体之前。

当包含board.h时,所有的piece.h都包含在board

之前

让类一起工作

1)你需要预先声明至少一个类。2)要使用类,编译器要么需要使用引用(或指针),要么需要知道类的大小。

class Board;

那么可以使用

void horizontal  ( Board & b );

不知道其大小

试着把这个放到"piece.h"的顶部

 class Board;
相关文章: