继承(通过文件)找不到类

Inheritance (through files) unable to find class?

本文关键字:找不到 文件 继承      更新时间:2023-10-16

我试图通过多个头文件和 cpp 文件为我正在编写的文本游戏使用继承。

有我的基础职业武器。哪个在文件中 武器.h

class Weapon
{
    public:
        string Name;
        int Damage;
        float ChanceToHit;
        int ExtraDamage;
        int Result;
        int Array[3];
        int Attack(int, int, string);
};

然后,我尝试将基础 Weapon.h 类继承为弓剑类。我确定我正确包含文件,但是当我尝试编译时,出现错误"错误:预期的类名类刀片:公共武器"Bow类的相同错误。

#include "Weapon.h"
#include "Crossbow.h"
using namespace std;
class Bow : public Weapon
{
    public:
        string Type = "Ranged";
        bool loaded;
    protected:
        Bow();
}; 
#include "Weapon.h"
class Blade : public Weapon
{
    private:
        string Type = "Melee";
    protected:

  void Draw();
};

有谁知道为什么会这样?谷歌也没有提出任何有用的东西。谢谢

MCVE (我认为)

//In Base.h
class Base
{
 public:
    int function();
 private:
};
//In Base.cpp
int Base::function()
{
    randomshit
    return 0;
}
//In Inherit.h
#include "Base.h"
class Inherit : public Base
{
public:
    int function():
private:
};
Getting error: "expected class name class Bow : public Weapon"

编辑:事实证明,我需要包括"#pragma 一次",这几乎解决了所有问题。谢谢你们的帮助。

您不使用任何包含保护,因此您的文件 Weapon.h 可能被多次包含,从而导致编译错误。

要了解有关包括警卫的更多信息:https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Include_Guard_Macro

然后,您的标头 Weapon.h 将变为:

#ifndef WEAPON_H_INCLUDED
#define WEAPON_H_INCLUDED
class Weapon
{
public:
    string Name;
    int Damage;
    float ChanceToHit;
    int ExtraDamage;
    int Result;
    int Array[3];
    int Attack(int, int, string);
};
#endif // WEAPON_H_INCLUDED

对所有其他头文件执行相同的操作。

完成此操作后,删除所有不必要的包含项并进行干净的重建。

这可能不是一个答案,但不可能将其作为评论发布

这在我的Visual Studio 2013上编译(但不链接!!)。

#include <string>
using namespace std;
class Weapon
{
    public:
        string Name;
        int Damage;
        float ChanceToHit;
        int ExtraDamage;
        int Result;
        int Array[3];
        int Attack(int, int, string);
};    
class Bow : public Weapon
{
    public:
        string Type = "Ranged";
        bool loaded;
    protected:
        Bow();
};     
class Blade : public Weapon
{
    private:
        string Type = "Melee";
    protected:    
        void Draw();
};

但是它可能会在较旧的编译器上失败,因为声明中的初始化为 string Type = "Melee";

请注意,using namespace std;在声明class Weapon之前