gpt4 book ai didi

c++ - 交叉依赖类的问题

转载 作者:行者123 更新时间:2023-11-27 23:36:20 25 4
gpt4 key购买 nike

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

//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.cpp 和成员 classes.files 中添加 figure.h 到 board.h Compiler Error C2027

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",否则编译器不知道 range 方法(在Board.cpp) 的 Figure 对象。

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

关于c++ - 交叉依赖类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58953976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com