C++:在 Base class 中使用函数调用 Derived class

C++: Using function calling Derived class in Base class

如何在 Base class 中使用 Derived class?

编辑 2: 在 main 中调用 virtual void move(Derived1 &race); 时,它不会编译,但会抛出 Derived1 is not found 的错误。当我在没有 Derived1 class 对象的情况下调用该函数时,它确实可以编译,但该函数似乎什么也没做。是否有可能使该功能起作用?

编辑:

基础class

class Base {
protected:
    int x, y;
    int moves;
    char name;
    bool free;
public:
    Base();
    virtual void move(Derived1 &race);
};

导出class1

class Derived1 : public Base {
private:
    const int x = 10;
    const int y = 60;
    Base ***track;
public:
    Derived1(int x = 10, int y = 60);
    void printBoard();
    Base ***getArray() const;
    ~Derived1();
    void move{}
};

导出class2

class Derived2 : public Base {
public:
    Derived2();
    Derived2(int x, int y);
    void move(Derived1& race);
};

Derived 2

的void move()函数

它检查阵列中的障碍物。如果找到空闲 space,它就会移动到那里。代码真的很糟糕,因为我还没有完成,只是在一切顺利之前的临时代码。

void Derived2::move(Derived1& race) {
    if (race.getArray()[x][y + 1]->getFree() == true) {
        delete[] race.getArray()[x][y];
        race.getArray()[x][y] = new Base();
    }
    if (race.checkFreeY(x, y + 1, 3) == true) {
        delete[] race.getArray()[x][y + 4];
        race.getArray()[x][y + 4] = new Derived2(x, y + 4);
        moves++;
    }
    else if (race.checkFreeX(x, y + 1, 3) == true) {
        delete[] race.getArray()[x + 3][y + 1];
        race.getArray()[x + 3][y + 1] = new Derived2(x + 3, y + 1);
        moves++;
    }
    else {
        moves++;
    }
}

作业是用 virtual move() 函数进行一场比赛,该函数用在所有其他 Derived class 中,它在二维数组中移动对象障碍。

编辑 3:

我要拨打的电话:

Derived1 track;
track.fillTrack();
track.genBushes();
track.genRacers();
track.getArray()[0][0]->move(track);

执行此操作时,出现以下错误:

syntax error: identifier 'Derived1'
'void Base::move(Derived1&)': overloaded member function not found in 'Base'
"void Base::move(<error-type> &race)"

如下编辑 Base 中的移动函数 virtual void move() {} 并尝试调用 track.getArray()[0][0]->move(); 我收到以下错误:

too few arguments in function to call

在定义Base之前你需要说

class Derived1;

这将使移动声明有效:

virtual void move(Derived1 &race);

您将需要提供 Base::moveDerived1::move 的定义(您可以通过将其标记为纯虚拟来删除对 Base::move 的需求)。