涉及继承和私有对象的特定问题,c ++

问题描述 投票:-1回答:1

我将尝试尽可能简洁地解决问题:

我有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。我根本无法弄清楚如何做到这一点,或者甚至可能。任何帮助将不胜感激。

c++ oop inheritance
1个回答
1
投票

你的injectRobot不知道任何Robot实例。应该怎么知道程序中的其他地方(在你的main中)有一个实例应该用于获取roboLocale对象,这对Robot类是私有的?

  1. 你的injectRobot必须有一个函数参数,你传入要注入的Robot实例(或至少它的位置,如果这是你唯一感兴趣的东西)。
  2. 你的qazxsw poi必须能够实际获取存储在qazxsw poi对象中的位置信息。

你可以尝试:

injectRobot
© www.soinside.com 2019 - 2024. All rights reserved.