gpt4 book ai didi

c++ - 错误 : expected ')' before '*' token in header

转载 作者:太空狗 更新时间:2023-10-29 20:11:41 24 4
gpt4 key购买 nike

我正在制作一个程序,其中有一个拥有剑的英雄。我为这两个类(class)开设了类(class)。在 header 中,我收到错误:expected ')' before '*' token on the line Sword(Hero* h); 在 Sword 的 header 中。这是完整的文件 (Sword.h):

#ifndef SWORD_H
#define SWORD_H

#include <Hero.h>

class Sword {
public:
Sword(Hero* h);
virtual ~Sword();
};

#endif // SWORD_H

Hero.h 与 Hero.h 在同一目录中,我使用的是 Code::Blocks。

我浏览了其他帖子,但找不到任何有用的信息,因此,我们将不胜感激。

编辑:这是 Hero.h 的内容:

#ifndef HERO_H
#define HERO_H

#include <string>
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>

#include <Sword.h>
#include <Sprite.h>
#include <Window.h>

class Hero : public Sprite {
public:
Hero(Window* w);
void update();
void event(SDL_Event e);
~Hero();
protected:
private:
bool up;
bool right;
bool left;
bool down;

Window* window;
Sword* sword;
};

#endif // HERO_H

最佳答案

您不能从 Hero.h 中包含 Sword.h 并从 Sword.h 中包含 Hero.h,包含链必须在某处停止。您可以使用前向声明来修复它:

//#include <Hero.h> // remove this

class Hero; // forward declaration

class Sword {
public:
Sword(Hero* h);
virtual ~Sword();
};

之所以可行,是因为您不需要 Hero 的定义在 Sword.h 中编译器只需要知道 Heroclass .

你可以在 Hero.h 中做同样的事情:替换 #include <Sword.h>class Sword; .然后,您可以在需要定义的相应 .cpp 文件中包含这些文件,以便使用这些类。

经验法则:始终使用前向声明,除非需要包含整个 header 。

进一步阅读:When can I use a forward declaration?

关于c++ - 错误 : expected ')' before '*' token in header,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31886183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com