C++:使用函数调用基类中的派生类

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

本文关键字:派生 基类 函数调用 C++      更新时间:2023-10-16

如何在Base类中使用Derived类?

第2版:在main中调用virtual void move(Derived1 &race);时,它不编译,而是抛出Derived1 is not found的错误。当我在没有Derived1类对象的情况下调用函数时,它确实进行了编译,但该函数似乎什么都不做。有可能让这个功能发挥作用吗?

编辑:

基类

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

派生类1

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{}
};

派生类2

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

派生2的void move()函数

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

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类,该函数在带有障碍物的2D阵列中移动对象。

编辑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)"

virtual void move() {}编辑Base中的移动函数,并尝试按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的需求)。