使用扩展类和派生类的方法
use the method of extended class and of derived
假设我有一个名为Foo
的类和一个扩展Foo
的名为Bar
的类。我通过指针将它们存储在矢量中:
class Foo {
void draw() {
// stuff
}
};
class Bar() : public Foo {
void draw() {
// stuff
}
}
vector<Foo*> someVector;
// put types of Foo and Bar in the vector
for (int i = 0; i < someVector.size(); i++) {
Foo &f = someVector[i];
// if it's of type bar it should
// use that draw method
f.draw();
}
现在它将始终使用Foo
的绘制方法。但是,如果它是Bar类型的,我怎么能让它使用Bar
的绘制方法呢?
编辑:多亏了Joe Z,我知道现在可以通过虚拟来实现这一点。但是如果它是"Bar"类型,而我想使用"Foo"的绘制方法呢?现在,对于虚拟,它总是选择"Bar"方法。
您需要使用virtual
方法。这告诉编译器使用多态调度(即在运行时查找要调用的正确方法)。
class Foo {
virtual void draw() {
// stuff
}
};
class Bar : public Foo {
virtual void draw() {
// stuff
}
};
这看起来像是一个合理的教程来解释这个概念:http://www.learncpp.com/cpp-tutorial/122-virtual-functions/
相关文章:
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 为什么此派生对象无法访问基类的后递减方法?
- 是否可以为 QPixmap 派生类嵌入缩放方法?
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 使用基类中的派生方法运行线程,而无需使用模板
- 是否可以使用基类非虚拟方法中的派生类虚拟方法?
- 在派生类中使用基类的私有成员变量的最佳方法
- 如何在从抽象基派生的类中实现相同的方法?
- 调用从模板派生的类的静态方法,而不指定模板
- 如何在工厂方法中返回指向基于基础操作系统的派生类的有效指针
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 从基类实例调用派生类方法而不进行强制转换
- 派生类调用父类的方法,该方法调用重写的虚拟方法调用错误的方法
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- 通过基类接受方法转发派生 UniquePtr 的右值会移动引用而不是复制
- C ++基础私有方法在将自身转换为派生类后可以访问吗?
- C++ 使用派生类方法更改基类数据成员
- 如何使用派生类特定的方法:派生类中的派生成员
- 使用抽象类的指针访问派生类的方法;派生类似乎也是抽象的