继承(通过文件)找不到类
Inheritance (through files) unable to find class?
我试图通过多个头文件和 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
之前。
相关文章:
- C++ ZBar cmake 错误"找不到文件"时包括
- 如何修复使用VScode调试器gcc调试时的"找不到文件"错误
- C++找不到文件
- Windows Subsystem for Linux (WSL) 下的间歇性随机"找不到文件"错误
- Makefile在Linux中工作,但在Windows下不起作用,在子目录中找不到文件
- Nemiver 找不到文件 /build/glibc-LK5gWL/glibc-2.23/stdlib/random.c
- 在 Windows 10 上找不到 ./****.h 文件 qt5,C++
- 找不到文件或目录
- ld:找不到文件:/usr/lib/crt1.o
- sip:找不到文件"QtGui/QtGuimod.sip"
- 生成文件错误 - 找不到文件 - *.cpp
- 错误53:找不到文件,而是路径中存在所有DLL
- YAML::LoadFile(std::string const&) 找不到文件 [ROS 中的 yaml-cpp]
- 在英特尔C++编译器 (Linux) 的配置搜索路径中找不到文件可执行文件
- CMake 包含错误(找不到文件、未定义引用)
- 尝试包含id3lib标头时出现找不到文件错误
- 在iOS设备上找不到文件QT创建者C QstandardPaths :: StandardLocations(Qs
- 生成可执行文件时找不到文件,但在eclipse c 中运行正常
- Rcpp:将C++函数移植到 R 中,'Rcpp.h'找不到文件
- CodeBlocks MinGW版本找不到文件,必须手动包含在链接器中