代码之家  ›  专栏  ›  技术社区  ›  randomehh

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

  •  -4
  • randomehh  · 技术社区  · 9 年前

    我如何使用 Derived 中的类 Base

    编辑2: 打电话时 virtual void move(Derived1 &race); 在main中,它不编译,但抛出错误 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() 每隔一次使用的函数 衍生的 类,该类在具有障碍物的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() {} 试着打电话 track.getArray()[0][0]->move(); 我收到以下错误:

    too few arguments in function to call

    1 回复  |  直到 9 年前
        1
  •  0
  •   Martin Bonner supports Monica    9 年前

    在定义 Base 你需要说

    class Derived1;
    

    这将使移动声明有效:

    virtual void move(Derived1 &race);
    

    您需要提供 Base::move Derived1::move (您可以不需要 底座::移动 通过将其标记为纯虚拟)。

    推荐文章