This question already has answers here:
Resolve build errors due to circular dependency amongst classes
                                
                                    (11个答案)
                                
                        
                                2年前关闭。
            
                    
我真的是C ++的新手,我正在尝试完成一个小项目来理解继承。我在包含和转发声明方面遇到问题。以下是似乎有问题的以下标头:

player.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


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

如果我将其用于cardException:

#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类试图从其继承时找不到BaseCardException类的定义。

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

07-24 09:30