已经多次发布,但没有一次能够回答我的情况。请帮助我解决我的错误:不允许使用数据成员初始化程序'出现在等号下面。这是包含问题的代码。
//Player.cpp :Contains information about the player
#include <iostream>
#include <string>
#include "Main.cpp"
using namespace std;
void Player()
{
struct Player {
int Charma = 0;
unsigned int Hunger = 10;
unsigned int Energy = 50;
unsigned int Health = 100;
};
enum Race {
UNKNOWN,
DEAD,
HUMAN,
ORC,
GOBLIN,
ELF,
LIZARD,
CAT,
VAMPIRE,
WEREWOLF,
SNK
};
}
答案 0 :(得分:1)
您收到该错误是因为您在声明struct
时正在初始化变量。这是不允许的。而是将初始化移动到struct的构造函数中。
但是,这不是代码中唯一的错误。您正在定义struct
函数内部的Player
(应该是构造函数)。您需要切换它们,以便Player
结构中包含Player
函数。这样结构将有一个构造函数,您可以在其中初始化值。另一件事,不要#include
.cpp文件。这是一种不好的做法。
您的代码应该是这样的:
struct Player {
int Charma;
unsigned int Hunger;
unsigned int Energy;
unsigned int Health;
Player() : Charma(0), Hunger(10), Energy(50), Health(100)
{
// do other constructor stuff here
}
};
答案 1 :(得分:0)
另一种想法是,如果你打算在Player
内部进行一些机械操作,你可以将声明移到真实的class
中。然后,您将能够更轻松地扩展项目。像这样:
标题强>
// #include "Item.h"
typedef enum RaceDef {
UNKNOWN,
DEAD,
HUMAN,
ORC,
GOBLIN,
ELF,
LIZARD,
CAT,
VAMPIRE,
WEREWOLF,
SNK
} PlayerRace;
class Player {
public:
Player(unsigned int Charma=0,
unsigned int Hunger=10,
unsigned int Energy=50,
unsigned int Health=100,
PlayerRace Race=HUMAN);
void attack(Player);
void slap(Player);
//void equipItem(Item);
void exercise(unsigned int duration);
void die();
void etc();
private:
unsigned int m_Charma;
unsigned int m_Hunger;
unsigned int m_Energy;
unsigned int m_Health;
unsigned PlayerRace m_Race;
Race m_Race;
};
<强> CPP 强>
Player::Player(unsigned int Charma,
unsigned int Hunger,
unsigned int Energy,
unsigned int Health,
PlayerRace Race):
m_Charma(Charma),
m_Hunger(Hunger),
m_Energy(Energy),
m_Health(Health),
m_Race(Race) {
//constructor code goes here
//e.g. if player starts with a random item :
// Item randomItem = ItemUtils.getRandomItem();
// equipItem(randomItem);
}
我希望这会有所帮助,祝你好运:)。