c++ - 转发声明类,但 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 个月前。提前致谢
解决方案
前向声明用于打破依赖循环。
但是当你需要定义时,声明是不够的,所以你可能需要在定义两个类之后移动一些东西。
在你的情况下,它会是这样的:
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;
}
推荐阅读
- java - 如何使用 PowerMock 测试调用另一个静态方法的静态方法?
- javascript - 为什么 ![] == {} 和 {} == ![] 结果不同
- javascript - 如何在 d3 数据键功能中使用值?
- javascript - 当我测试 app.js 时出现问题
- slack - 如何确定工作区是否添加或删除了您的 Slack 应用程序?
- html - 对齐和
- docker - 如何使用 Jenkins 声明式管道在远程 Docker 服务器上构建?
- asp.net - 使用模型数据进行 jqueryui 自动完成的有效方法
- ruby-on-rails - FactoryBot ActiveRecord::RecordInvalid:验证失败:需要年份
- spring - Consul 用于微服务架构中的身份验证