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

时间:2022-01-26 04:29:25

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. So I am not able to include the Condition class twice. Am I wright?

问题是我想在GameHandler类中分配一个Condition对象(不是指针),如下例所示,但是我不能这样做,因为我想到引擎类中包含的Condition.h。所以我无法两次包含Condition类。我怀疑吗?

What can I do to get a solution that works kind like my wrong example?

我能做些什么来获得一个像我错误的例子一样的解决方案?

Thank you a lot!!!

非常感谢!!!

Condition.h:

#ifndef CONDITION_h
#define CONDITION_h

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

#endif

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

#ifndef GAMEHANDLER_h
#define GAMEHANDLER_h

#include "Condition.h"

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

#endif

2 个解决方案

#1


0  

By default, class members are private in C++ (more about access specifiers here). Try declaring them as public.

默认情况下,类成员在C ++中是私有的(更多关于访问说明符)。尝试将它们声明为公开。

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.

另外,你不能在类的声明中调用方法!你必须在一个方法(例如,构造函数)中完成它,但是where将取决于你想做什么。

class GameHandler
{
  Condition condition_;

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

#2


0  

Using :

#ifndef GAMEHANDLER_h
#define GAMEHANDLER_h

/.../

#endif

Will prevent multiple inclusion, so it doesn't matter if you include your header multiple times

会阻止多次包含,所以如果多次包含标题并不重要

#1


0  

By default, class members are private in C++ (more about access specifiers here). Try declaring them as public.

默认情况下,类成员在C ++中是私有的(更多关于访问说明符)。尝试将它们声明为公开。

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.

另外,你不能在类的声明中调用方法!你必须在一个方法(例如,构造函数)中完成它,但是where将取决于你想做什么。

class GameHandler
{
  Condition condition_;

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

#2


0  

Using :

#ifndef GAMEHANDLER_h
#define GAMEHANDLER_h

/.../

#endif

Will prevent multiple inclusion, so it doesn't matter if you include your header multiple times

会阻止多次包含,所以如果多次包含标题并不重要