C++:使用函数调用基类中的派生类
C++: Using function calling Derived class in Base class
如何在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::move
和Derived1::move
的定义(您可以通过将其标记为纯虚拟来消除对Base::move
的需求)。
相关文章:
- 如何通过派生类函数更改基类中的向量
- 如何使用基类指针引用派生类成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 为什么此派生对象无法访问基类的后递减方法?
- 使用基类中的派生方法运行线程,而无需使用模板
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 在派生类中使用基类的私有成员变量的最佳方法
- 基类和派生类的多态赋值运算符
- 如何在从抽象基派生的类中实现相同的方法?
- 基类的填充将被复制到派生类中
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 指向基类派生类的 std::unique_ptr 的指针
- 为什么基类数据在派生类数据之前初始化
- c++ 派生基类 Friend 函数访问父级上的私有函数
- 如何将基类替换为派生基类
- 当基类未指定构造函数时,如何使用仅具有带参数的构造函数的类派生基类?
- 解析公用派生基类模板中的函数模板名称时出错"Not declared in this scope"