交叉依赖项类的问题

Problems with cross dependency classes

本文关键字:问题 依赖      更新时间:2023-10-16

我对这部分代码有问题。 编译器说我不能使用指向未完成类的指针。 我已经尝试在图类中使用包括板类和在板中使用图,但这会导致编译器出现严重问题,并且出现了一大堆错误。(#pragma 一次和/或头球中的守卫被使用(

//Board.h
class Figure;
class Board
{
Figure *sz[8][8];
...
public:
void showRange();
friend class Figure;
};
//-------------------
//Board.cpp
void Board::showRange()
{
    for (int i = 0; i < 8; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            if(sz[j][i])
                sz[j][i]->range();
        }
    }
    this->display();
}
...
//Figure.h
class Board;
class Figure
{
protected:
    Board *s;                       
    int x, y;                               
public:
    virtual void range() = 0;
    friend class Board;
};
//range funcions are defined in member classes 

[编辑1] 将 figure.h 添加到 board.h 编译器错误 C2027 在图.cpp和成员类文件中

Severity Code Description Project File Line Suppression State
Error C2027 use of undefined type 'Board' ..figure.cpp 7
Error C2027 use of undefined type 'Board' ..figure.cpp 15
Error C2027 use of undefined type 'Board' ..figure.cpp 17
Error C2027 use of undefined type 'Board' ..figure.cpp 25
Error C2027 use of undefined type 'Board' ..figure.cpp 26
Error C2027 use of undefined type 'Board' ..bishop.cpp 7
Error C2027 use of undefined type 'Board' ..bishop.cpp 13
Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0393   pointer to incomplete class type is not allowed ..Figure.cpp   7   
Error (active)  E0393   pointer to incomplete class type is not allowed ..Figure.cpp   15  
Error (active)  E0393   pointer to incomplete class type is not allowed ..Figure.cpp   17  
Error (active)  E0393   pointer to incomplete class type is not allowed ..Figure.cpp   26  
Error (active)  E0393   pointer to incomplete class type is not allowed ..Figure.cpp   25

Board.cpp必须#include "Figure.h",否则编译器不知道Figure对象range方法(在Board.cpp中调用(。

顺便问一下:你为什么需要朋友声明? 它通常表明设计不佳。