简体   繁体   English

C++在两个头文件中包含一个类

[英]C++ include a class in two header files

I have to get a project done for university but I can not figure out how it can be done.我必须为大学完成一个项目,但我不知道如何完成。

The problem is that I want to allocate a Condition object (not a Pointer) in the GameHandler Class like in the example below, but I can not do this because I think of the included Condition.h in the Engine Class.问题是我想在 GameHandler 类中分配一个条件对象(不是指针),如下例所示,但我不能这样做,因为我想到了引擎类中包含的 Condition.h。 So I am not able to include the Condition class twice.所以我无法两次包含 Condition 类。 Am I wright?我是赖特吗?

What can I do to get a solution that works kind like my wrong example?我该怎么做才能获得像我的错误示例一样有效的解决方案?

Thank you a lot!!!十分感谢!!!

Condition.h:条件.h:

#ifndef CONDITION_h
#define CONDITION_h

class Condition
{
  enum Rank {FIRST, SECOND, THIRD};
  void doSomething();
};

#endif

Engine.h引擎.h

#ifndef ENGINE_h
#define ENGINE_h

#include "Condition.h"

class Engine
{
  Condition::Rank getter();
};

#endif

But now I have a third Class which should look like this where I want to create a Condition Object (not a Pointer).但是现在我有了第三个类,它看起来应该像这样,我想在其中创建一个条件对象(而不是指针)。 How can this be done?如何才能做到这一点?

GameHandler.h GameHandler.h

#ifndef GAMEHANDLER_h
#define GAMEHANDLER_h

#include "Condition.h"

class GameHandler
{
  Condition condition_;
  condition_.doSomething();
}

#endif

Using:使用:

#ifndef GAMEHANDLER_h
#define GAMEHANDLER_h

/.../

#endif

Will prevent multiple inclusion, so it doesn't matter if you include your header multiple times将防止多次包含,所以如果你多次包含你的标题并不重要

By default, class members are private in C++ (more about access specifiers here ).默认情况下,类成员在 C++ 中是私有的(有关访问说明符的更多信息,请参见此处)。 Try declaring them as public.尝试将它们声明为公开的。

class Condition
{
public:
  enum Rank {FIRST, SECOND, THIRD};
  void doSomething();
};

Also, you cannot call a method within the declaration of a class, You'd have to do it inside a method (for example, the constructor), but the where will depend on what do you want to do.此外,您不能在类的声明中调用方法,您必须在方法(例如,构造函数)中调用方法,但是在哪里将取决于您想要做什么

class GameHandler
{
  Condition condition_;

public:
  GameHandler() {
    condition_.doSomething();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM