gpt4 book ai didi

c++ - 尝试将新类型合并到现有类型时出现错误 C2079 和错误 C2440

转载 作者:行者123 更新时间:2023-11-30 03:57:24 24 4
gpt4 key购买 nike

我不太清楚为什么会出现这些错误,我以为是因为我需要前向声明,但问题仍然存在。我不知道是什么原因造成的。我把评论放在有问题的地方。寻找关于为什么会发生这种情况的解释和解决方案。谢谢。

// Player.h

#ifndef PLAYER_H
#define PLAYER_H

#include "Weapon.h"
#include "Monster.h"
#include <string>

// Forward declaration
class Race;

class Player
{
public:
Player();

/* Return Type Method Name */
bool IsDead();
std::string GetName();
int GetArmor();

void TakeDamage(int damage);
void CreateClass();
bool Attack(Monster& monster);
void LevelUp();
void Rest();
void ViewStats();
void Victory(int xp, Monster* monster);
void GameOver();
void DisplayHitPoints();
void SetRace();

private:
/* Type Name */
std::string m_Name;
std::string m_ClassName;
int m_Accuracy;
int m_HitPoints;
int m_MaxHitPoints;
int m_ExpPoints;
int m_NextLevelExp;
int m_Level;
int m_Armor;
int m_Gold;
Weapon m_Weapon;
Race m_Race; // problem: error C2079 uses undefined class 'Race'

};

#endif // PLAYER_H

带有无法从“种族”转换为“整数”错误的违规方法

void Player::SetRace()    
{
Race race;
m_Race = race.SelectRace(); // problem: error C2440 cannot convert from 'Race' to int
}

种族定义:

// Race.h

#ifndef RACE_H
#define RACE_H

#include <string>

class Race
{
public:
Race();

/* Return Type Method Name*/
Race SelectRace();
protected:

std::string GetName();

/* Type Name*/
std::string m_Name;
int m_Accuracy;
int m_HitPoints;

};

// ...below here implements multiple derived classes of type race

#endif // RACE_H

最佳答案

是的,正如您所发现的,前向声明在这里是不够的。那是因为Player中有Race类型的成员。

在 player.h 的顶部包含整个标题:

#include "Weapon.h"
#include "Monster.h"
#include "Race.h"

然后 Race 类的定义将对 Player 的定义可见。

关于c++ - 尝试将新类型合并到现有类型时出现错误 C2079 和错误 C2440,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28013740/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com