首页 > 解决方案 > 转发声明类,但 Visual Studio 忽略它

问题描述

//Code for a simple game I am making
#include <iostream>
#include <stdlib.h>
#include <Windows.h>
#include <conio.h>
#include <algorithm>
#include <string>

using namespace std;
class Enemy;
class Player{
    public:
        int health=10;
        int damage=(rand() % 5);
        void attack(Enemy enemy, string log){
            enemy.health=enemy.health-damage;
            cout << "You dealt " << damage << " to enemy!" << endl;
        }
};
class Enemy{
    public:
        int health=10;
        int damage=(rand() % 5);
        void attack(Player player, string log){
            player.health=player.health-damage;
            cout << "Your enemy dealt " <<  damage << " to you!";
        }
};
Player p1;
Enemy e1;

错误:

Severity    Code    Description Project File    Line    Suppression State
Error   C2027   use of undefined type 'Enemy'   Line 15

你能帮我解决这个错误吗?我刚开始编程 2-3 个月前。提前致谢

标签: c++

解决方案


前向声明用于打破依赖循环。

但是当你需要定义时,声明是不够的,所以你可能需要在定义两个类之后移动一些东西。

在你的情况下,它会是这样的:

class Enemy;
class Player
{
public:
    int health = 10;
    int damage = (rand() % 5);
    void attack(Enemy& enemy);
};
class Enemy
{
public:
    int health = 10;
    int damage = (rand() % 5);
    void attack(Player& player)
    {
        player.health -= damage;
        std::cout << "Your enemy dealt " << damage << " to you!";
    }
};

inline void Player::attack(Enemy& enemy)
{
    enemy.health -= damage;
    std::cout << "You dealt " << damage << " to enemy!" << std::endl;
}

推荐阅读