如何在Base
类中使用Derived
类?C++:使用函数调用基类中的派生类
编辑2: 当调用主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
的派生2它检查在阵列障碍
class Derived2 : public Base { public: Derived2(); Derived2(int x, int y); void move(Derived1& race); };
空隙移动()函数。如果找到空闲空间,它将在那里移动。代码非常糟糕,因为我还没有完成它,只是一个临时代码,然后我才顺利完成所有工作。
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)"
编辑移动功能在Base
如下virtual void move() {}
并试图调用像track.getArray()[0][0]->move();
我收到以下错误:
too few arguments in function to call
为什么基类需要获取派生类的实例? –
问题并不清楚......请添加一段关于如何使用'Derived'的片段。 –
'派生'有一个2D动态数组指针。我必须调用它才能使用它。忘记在代码中添加。 – randomehh