Town.h
class Town;
Tailor.h
#include "Town.h"
class Bully;
#include "Bully.h"
class Tailor
{
public:
//LookAround is called only in randWalk
void lookAround(Town & town, const short direction, const Bully bully[]);
//THIS is the code inside randwalk that calls bully
if(!bully[0].punch(*this,town))
void randWalk(Town & town, const Bully bully[]);
private:
}
Bully.h
#include "Town.h"
class Tailor;
#include "Tailor.h"
class Bully
{
public:
bool punch(Tailor& tailor, Town & town);
private:
}
的main.cpp
#include "Town.h"
#include "Tailor.h"
#include "Bully.h"
int main()
{
const char PLAYER_NAME[] = "Milhouse";
Bully bully_team[5];
//create a town
Town r(10,40,25);
//create a Tailor player called PLAYER_NAME and place him at 2,3
Tailor player(PLAYER_NAME);
player.placeMe(r);
//make the character move 12 times
for(int i = 0; i < 100; i++)
{
player.randWalk(r, bully_team);
}
return 0;
}
问题是我需要在Player函数中访问Bully类型的数组,但是Bully需要类型Player才能运行。这个Bully数组需要在main中声明。我一直在尝试许多不同的转发类的方法,但我似乎无法让它工作。
In file included from Tailor.h:8:0,
from main.cpp:7:
Bully.h:43:17: error: 'MAX_NAME_LENGTH' was not declared in this scope
char m_name[MAX_NAME_LENGTH];
^
Bully.h: In function 'std::ostream& operator<<(std::ostream&, const Bully&)':
Bully.h:31:33: error: 'const class Bully' has no member named 'm_name'
int length = strlen(bully.m_name);
^
Bully.h:35:23: error: 'const class Bully' has no member named 'm_name'
cout << bully.m_name[i];
^
In file included from Tailor.h:8:0,
from Tailor.cpp:1:
Bully.h:43:17: error: 'MAX_NAME_LENGTH' was not declared in this scope
char m_name[MAX_NAME_LENGTH];
^
Bully.h: In function 'std::ostream& operator<<(std::ostream&, const Bully&)':
Bully.h:31:33: error: 'const class Bully' has no member named 'm_name'
int length = strlen(bully.m_name);
^
Bully.h:35:23: error: 'const class Bully' has no member named 'm_name'
cout << bully.m_name[i];
^
Tailor.cpp: In member function 'void Tailor::lookAround(Town&, short int, const Bully*)':
Tailor.cpp:70:34: error: passing 'const Bully' as 'this' argument discards qualifiers [-fpermissive]
if(!bully[0].punch(*this,town))
^
In file included from Tailor.h:8:0,
from Tailor.cpp:1:
Bully.h:27:10: note: in call to 'bool Bully::punch(Tailor&, Town&)'
bool punch(Tailor& tailor, Town & town);
^
答案 0 :(得分:1)
使用此订单:
Player
和Bully
Player
和Bully
Player
和Bully
以及main
2.中的订单可能很重要。 Player
和Bully
中只有一个可以依赖于另一个的定义,并且该依赖关系确定哪个必须在另一个之后定义。没有依赖关系的那个最多取决于另一个的声明。声明一个带有指向数组的指针的函数不需要定义指向的类型,因此Player
显然不依赖于Bully
的定义。
1.和3.中的顺序并不重要,如果您愿意,可以在单独的翻译单元(源文件)中定义每个功能。