【发布时间】:2016-03-27 09:57:35
【问题描述】:
如何在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);
};
Derived 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++;
}
}
任务是使用在所有其他 Derived 类中使用的 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的sn-p。 -
Derived有一个二维动态指针数组。我必须调用它才能使用它。忘记在代码中添加了。 -
@randomehh 最好的方法是在子进程中覆盖父方法
-
几乎总是需要真正的代码。
标签: c++ function inheritance derived-class base-class