如何避免循环依赖这些代码:
Mechanic.cpp:
#include "stdafx.h"
#include "Characters.h"
#include "Monsters.h"
using namespace characters;
using namespace monsters;
using namespace std;
void character::character_atack(character const cha, monster &monst)
{
if (cha.dexterity + k(20) >= monst.defense)
monst.health = monst.health - cha.strength;
}
int k(int const max)
{
return (rand() % max);
}
void monster::monster_atack(character &cha, monster const monst)
{
if (monst.atack + k(20) >= cha.dexterity)
cha.health = cha.health - monst.damage;
}
Monsters.h:
#include <iostream>
#include <string>
namespace monsters
{
using namespace std;
class monster{
protected:
string name;
public:
int atack;
int damage;
int health;
int defense;
monster(int atk, int dmg, int hp, int def) : atack(atk), damage(dmg),
health(hp), defense(def) {}
~monster();
void monster_atack(character &cha, monster const monst);
};
class greenskins:monster{
greenskins(int atk, int dmg, int hp, int def) : monster(atk, dmg, hp, def) {}
};
}
Characters.h:
#include <iostream>
#include <string>
#include <vector>
namespace characters
{
using namespace std;
class character{
protected:
int level;
int experience;
string name;
public:
int health;
int strength;
int intelligence;
int dexterity;
struct position{
int x;
int y;
}pos;
character(int str, int in, int dex) : strength(str), intelligence(in),
dexterity(dex), level(1), experience(0) {
cout << "What's your name?" << endl;
cin >> name; }
~character();
void info_character();
void character_atack(character const cha, monster &monst);
};
}
编译器给我这样的错误:
Error 1 error C2061: syntax error : identifier 'monster'
要么
Error 9 error C2511: 'void monsters::monster::monster_atack(characters::character &,const monsters::monster)' : overloaded member function not found in 'monsters::monster'
最佳答案
问题是character
具有接受monster&
的函数,而monster
具有接受character&
的函数,但是在两种情况下都不会声明另一个类。值得庆幸的是,由于您只是在两个地方都将类作为参数传递(而不是让它们成为成员或某物),因此在两个地方都向前声明两个类就足够了:
// in character.h
namespace monsters {
class monster; // just fwd-declare
}
namespace characters {
class character {
// as before
};
}
和其他文件中的类似。
[更新]另外,您只是在头文件中的
monster
中引用class character
,需要将其限定为monsters::monster
。关于c++ - C2061-循环依赖,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26763887/