【发布时间】:2017-10-07 22:59:45
【问题描述】:
我对 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
使用这个 cardException.h 我得到错误:cardException.h: error: expected class-name before ‘{’ token 和 cardException.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 BaseCardException 和 CardException.h: error: ‘Player’ does not name a type。
如果同时使用前向声明:cardException.h:8:7: error: multiple types in one declaration
class BaseCardException 和 cardException.h: error: invalid use of incomplete type ‘class BaseCardException’
我只是想知道我在这里做错了什么?
【问题讨论】:
-
class abstractPlayerBase.h;是错误且不必要的前向声明。另外,请注意编译器报告的错误实际上可能是由于包含的文件中的错误代码造成的。 -
player.h 中的
class abstractPlayerBase.h语法无效。这将导致任何包含 player.h 的头文件的编译中断。与其阅读编译器发出的 LAST 错误消息,不如回滚并阅读 FIRST。第一条错误消息更可能代表一个实际问题,而最后一条错误消息很可能是因为编译器被早期的问题弄糊涂了。 -
您有循环包括 -
player.h包括cardException.h,其中包括baseCardException.h,其中包括player.h。见stackoverflow.com/questions/625799/…
标签: c++ c++11 inheritance forward-declaration