【问题标题】:Inheritance (through files) unable to find class?继承(通过文件)找不到类?
【发布时间】:2016-03-08 09:39:18
【问题描述】:

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

我有自己的基类武器。在文件 Weapon.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 and Sword 类。我确定我正确地包含了该文件,但是当我尝试编译时,我得到了错误 "error: expected class name class Blade : public Weapon" 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 once”,这几乎解决了所有问题。谢谢大家的帮助。

【问题讨论】:

  • 您在哪一行得到错误? crossbow.h 中有什么内容?
  • 可能是循环包含依赖项。但是你为什么#include "CrossBow.h"
  • @MichaelWalz 我在“class Bow”行中收到错误,与 Blade 类相同。对于弩,我继承弓类。我只是在其中包含了#include,因为我想不出任何其他可以解决我的问题的方法。我在 Crossbow.h 文件中也遇到了问题。出于某种原因,当我在同一个文件中继承时,我没有遇到问题。
  • @juanchopanza 我想不出还有什么可做的,所以我开始随机包含其他文件,希望它能修复它,但我还没有删除它们。同样由于某种原因,当我从同一个文件中继承时,我没有遇到问题。
  • 你可以添加错误吗?

标签: c++ class inheritance


【解决方案1】:

您没有使用任何包含保护,因此您的文件 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

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

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

【讨论】:

  • 不鼓励仅链接答案 - 添加更多详细信息
【解决方案2】:

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

这在我的 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 的声明之前。

【讨论】:

  • 谢谢,我可能会重新开始,看看问题是否仍然存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-20
  • 2011-07-30
  • 1970-01-01
  • 2014-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多