c++ - 充斥着标识符错误

标签 c++ inheritance include virtual-functions undeclared-identifier

我一直在为最终项目编写大富翁游戏。所以我认为我进展顺利,并且我已经用我的伪代码解决了所有问题。但是,我似乎忘记了如何正确处理包含,我知道这是问题所在,因为我能够将其改进到这一点,但我不确定如何修复它。

在我的代码的这个 super 精简版本中,我有三个 .h 文件“Space.h”,它是一个抽象/虚拟类,必须由各种不同的空间继承,这些空间可以出现在典型的大富翁棋盘上:属性(property)、 jail 、税收、机会、公益金等。必须继承的功能是 run(Player&),这就是当您降落在棋盘上的特定空间时“运行”的内容,所有使用 run 的函数都使用通过参数传递的播放器。

#pragma once
#include <string>
#include "Player.h"

class Space
{
public:
    virtual void run(Player&) = 0;
};

我的第二个 .h 文件是从 Space 继承的“Property.h”

#pragma once
#include "Space.h"

class Property : Space
{
public:
    void run(Player&) override;
    int i{ 0 };
};

最后我有“Player.h”,它有两个变量,一个名称和一个它拥有的属性 vector 。

#pragma once
#include <string>
#include <vector>
#include "Property.h"

class Player
{
public:
    std::string name{ "foo" };
    void addProperty(Property p);
private:
    std::vector <Property> ownedProperties;
};

这是一个非常基本的属性实现

#include "Property.h"
#include <iostream>

void Property::run(Player & p)
{
    std::cout << p.name;
}

播放器实现

#include "Player.h"
#include <iostream>

void Player::addProperty(Property p)
{
    ownedProperties.push_back(p);
}

最后是主线

#include "Player.h"
#include "Space.h"
#include "Property.h"

int main()
{
    Player p{};
    Property prop{};
    prop.run(p);
    system("pause");
}

每次运行时,我都会遇到一系列错误,我确信它必须对循环包含逻辑执行某些操作,其中玩家包括属性,属性包括空间,其中包括玩家。但是,我没有看到考虑到需要 #include 才能知道所有内容是如何定义的解决方法,不是吗?或者这些错误是否涉及其他内容?

enter image description here

最佳答案

您遇到循环包含问题。玩家包括属性,属性包括空间,空间又包括玩家。

您可以通过在 Space.h 中不包含 Player.h 并仅向前声明类来打破循环

#pragma once

class Player;

class Space
{
public:
    virtual void run(Player&) = 0;
};

关于c++ - 充斥着标识符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47706978/

相关文章:

C++,删除类头中的#include<vector> 或#include<string>

php - 为什么 PHP 会在本地包含的函数中抛出 "Cannot Redeclare"错误?

c++ - 多态类的隐式析构函数可以变为虚拟的吗?

c++ - 模块化和灵活的编程

c++ - 如何为子函数指定模板参数?

C++ 位串到int的转换

C++ 接口(interface)实现和子类对象实例化

c++ - C++ 中 'Using' 关键字应用于派生类的缺点

c++ - C++中的继承。为什么错了?

c - VS2010 "Cannot open include file"错误