специфическая проблема, включающая наследование и закрытый объект, c ++ - PullRequest
0 голосов
/ 03 марта 2019

Я постараюсь сделать мою задачу максимально лаконичной:

У меня есть 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();
}

Inмой класс World под void injectRobot() Я пытаюсь получить доступ к функциям robotLocale getX () и getY (), чтобы «внедрить» робота в мой World::arr.Я просто не могу понять, как это сделать, или вообще возможно ли это.Любая помощь будет принята с благодарностью.

1 Ответ

0 голосов
/ 04 марта 2019

Ваш injectRobot не знает ни о каких Robot экземплярах.Откуда ему знать, что где-то еще в программе (в вашем main) есть экземпляр, который следует использовать для извлечения объекта roboLocale, который, кроме того, private , в класс Robot?

  1. Ваш injectRobot должен иметь параметр функции, в который вы передаете экземпляр Robot для инъекции (или, по крайней мере, его позицию, если это единственное, что вас интересует).
  2. Ваш injectRobot должен иметь возможность фактически получать информацию о местоположении, хранящуюся в этом Robot объекте.

Вы можете попробовать:

#include <array>
#include <iostream>

class Point
{
private:
    int _x{};
    int _y{};

public:

    // Default constructor to prevent uninitialized values
    Point() = default;

    Point(int x, int y) 
        : _x(x), _y(y) { }

    void set(int x, int y)
    {
        _x = x;
        _y = y;
    }

    int x() const { return _x; }
    int y() const { return _y; }
};

class Robot 
{
private:
    Point _robolocale;
public:
    Robot() = default;
    Robot(int x, int y) : _robolocale(x, y) {}
    Point const& pos() const { return _robolocale; }
};

class World
{
private:
    char arr[10][10];
public:
    World()
    {
        std::fill(arr[0], arr[0] + 10 * 10, ' ');
    }
    // Which robot should be injected? 
    // We need to pass a robot in because otherwise there is none to inject
    void injectRobot(Robot const& r)
    {
        arr[r.pos().x()][r.pos().y()] = '@'; // 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 robot1;
    Robot robot2(7, 4);

    field.injectRobot(robot1);
    field.injectRobot(robot2);

    field.displayField();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...