循环包括和转发声明类

Circular include and forward declaration classes

本文关键字:声明 转发 包括 循环      更新时间:2023-10-16

我真的是c++的新手,我正在尝试完成一个小项目来理解继承。我在包含和转发声明方面遇到问题。以下是以下似乎有问题的标头:

玩家.h:

#ifndef PLAYER_H
#define PLAYER_H
#include "abstractPlayerBase.h"
#include "cardException.h"
class abstractPlayerBase;
class Player: public AbstractPlayerBase
{
   ...
   //a function throws a CardException
};
#endif

baseCardException.h:

#ifndef BASECARDEXCEPTION_H
#define BASECARDEXCEPTION_H
#include "Player.h"
class BaseCardException
{
...
};
#endif

cardException.h:

#ifndef CARDEXCEPTION_H
#define CARDEXCEPTION_H
#include "baseCardException.h"
class Player; //the problem seems to be here
class CardException: public BaseCardException
{
public:
    CardException(const Player& p);
};
#endif

使用此卡异常.h 我得到错误:cardException.h: error: expected class-name before ‘{’ tokencardException.h: error: multiple types in one declaration

如果我将其用于卡异常:

#ifndef CARDEXCEPTION_H
#define CARDEXCEPTION_H
#include "baseCardException.h"
class BaseCardException; //this changed
class CardException: public BaseCardException
...

错误:发生cardException.h: error: invalid use of incomplete type ‘class BaseCardException’ class CardException: public BaseCardExceptionCardException.h: error: ‘Player’ does not name a type

如果同时使用前向声明:cardException.h:8:7: error: multiple types in one declaration class BaseCardExceptioncardException.h: error: invalid use of incomplete type ‘class BaseCardException’

只想知道我在这里做错了什么?

BaseCardException.h 似乎包含一个名为 CardException 的类的

声明,但您的命名约定似乎表明它应该包含一个名为 BaseCardException 的类。

您收到错误是因为编译器在 CardException 类尝试从 BaseException 类继承时找不到该类的定义。

另外,AbstractPlayerBase 类的定义在哪里?