2017-06-02 77 views
0

我是一年级的大学生,不知道关于CS的一切,所以请耐心等待我的新鲜感,这是我的第一个问题。3级与循环之间的循环依赖性问题

对于一项任务,我们正在制作口袋妖怪的虚拟版本去实践使用C++中的多态,并且我遇到了一些编译错误。这里有三个文件,只需在它们的代码样本:

#ifndef EVENT_H 
#define EVENT_H 

#include <string> 
#include "Trainer.h" 

class Event{ 
    protected: 
     std::string title; 
    public: 
    Event(); 
    ~Event(); 

    virtual void action(Trainer) = 0; 

}; 
#endif 

Trainer.h:

#ifndef TRAINER_H 
#define TRAINER_H 
#include "Pokemon.h" 
class Trainer{ 
    private: 
     Pokemon* pokemon; 
     int num_pokemon; 
    public: 
     Trainer(); 
     ~Trainer(); 
    //include accessors and mutators for private variables  
}; 
#endif 

Pokemon.h:

#ifndef POKEMON_H 
#define POKEMON_H 
#include "Event.h" 
#include <string> 
class Pokemon : public Event{ 
    protected: 
     std::string type; 
     std::string name; 
    public: 
     Pokemon(); 
     ~Pokemon(); 
     virtual bool catch_pokemon() = 0; 

}; 
#endif 

的trainer.h文件为每个小宠物类型(例如Rock)定义一些虚拟功能的父类。我得到的错误是,当我编译这一切,我得到的东西,说:

Pokemon.h : 5:30: error: expected class-name befoer '{' token: 
    class Pokemon : Event { 

口袋妖怪需要一个派生类的事件,这样的事件指针可以指向另一个位置班级可以指向任务的口袋妖怪,pokestop,或洞穴,我一直在网上查找几个小时,不知道该怎么做。我将不胜感激帮助!如果您需要更多信息或其他信息,请告知我,这是我第一次发布问题。

回答

0

您需要一些前向声明。

在Event.h中,您可以将class Trainer;而不是#include "Trainer.h"。在Trainer.h中,您可以输入class Pokemon;而不是#include "Pokemon.h"

为了实际使用其他类,您可能需要在相应的源文件中包含适当的头文件。但是通过避免在头文件中包含,你摆脱了循环依赖问题。

Pokemon.h必须继续到#include "Event.h",因为您继承Event,这需要一个完整的定义。

+0

非常感谢!我在其他关于使用前向声明的问题上看到了一些东西,但是如果您使用了2个类,它们只会与之相关。使用它们有什么缺点,或者它们对于面向对象的东西是非常必要的? – Dula

0

使用前向声明来告诉类他们需要使用的类型将在稍后定义。您可以在大小已知的情况下使用前向声明,指针和引用始终具有相同的大小,而不管它们指向哪种类型,以便使用它们。

#ifndef EVENT_H 
#define EVENT_H 

#include <string> 

class Trainer; 
class Event 
{ 
protected: 
    std::string title; 

public: 
    Event(); 
    virtual ~Event(); 

    virtual void action(Trainer* const trainer) = 0; 

}; 
#endif 

然后

#ifndef TRAINER_H 
#define TRAINER_H 

class Pokemon; 
class Trainer 
{ 
private: 
    Pokemon* const pokemon; 
    int numPokemon; 
public: 
    Trainer(); 
    ~Trainer(); 
}; 
#endif 

然后

#ifndef POKEMON_H 
#define POKEMON_H 
#include "Event.h" 
#include <string> 
class Pokemon : public Event 
{ 
protected: 
    std::string type; 
    std::string name; 
public: 
    Pokemon(); 
    virtual ~Pokemon(); 
    virtual bool catchPokemon() = 0; 
}; 
#endif 
使用多态(虚拟函数)时

,你必须始终基类的析构函数虚也。使派生类析构函数也是虚拟的也很好,但它不是必需的。