我将尝试尽可能简洁地解决问题:
我有3个类,一个机器人类,Point类和一个世界级。
class Point
{
private:
int x;
int y;
public:
void set(int x, int y)
{
this->x = x;
this->y = y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
class Robot{
private:
Point roboLocale;
public:
Robot()
{
}
void init()
{
roboLocale.set(0, 0);
}
class World
{
private:
char arr[10][10];
public:
World()
{
std::fill(arr[0], arr[0] + 10 * 10, ' ');
}
void injectRobot()
{
arr[roboLocale.getX()][roboLocale.getY()] = '@'; // would like to access robotLocales x and y coords
}
void displayField()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
std::cout << "[" << arr[i][j] << "]";
}
std::cout << std::endl;
}
}
};
int main()
{
World field;
Robot robot;
robot.init();
field.injectRobot();
field.displayField();
}
在void injectRobot()
下的我的世界级中,我试图访问robotLocale
getX()和getY()成员函数,将机器人“注入”我的World::arr
。我根本无法弄清楚如何做到这一点,或者甚至可能。任何帮助将不胜感激。
你的injectRobot
不知道任何Robot
实例。应该怎么知道程序中的其他地方(在你的main
中)有一个实例应该用于获取roboLocale
对象,这对Robot
类是私有的?
injectRobot
必须有一个函数参数,你传入要注入的Robot
实例(或至少它的位置,如果这是你唯一感兴趣的东西)。你可以尝试:
injectRobot