【发布时间】:2020-07-30 08:50:59
【问题描述】:
我来自 Python 背景,目前正在学习 C++ 中的 OOP。
我在弄清楚如何让代码调用继承到 HelperChild 的帮助器类 HelperBase 中的正确方法时遇到问题。
#include <iostream>
class HelperBase {
public:
HelperBase() {}
virtual void something() {
std::cout << "HelperBase" << std::endl;
}
};
class HelperChild : public HelperBase {
public:
HelperChild() {}
void something() {
std::cout << "HelperChild" << std::endl;
}
};
我在Base 类中使用的HelperBase 类,它被设置为成员变量。
class Base {
public:
Base(HelperBase &helperBase) : hb(helperBase) {}
virtual void print() {
std::cout << "-- Base" << std::endl;
hb.something();
}
HelperBase hb;
};
那么这个类作为类Child的基类:
class Child : public Base {
public:
Child(HelperChild &helperChild) : Base(helperChild) {
helperChild.something();
}
};
main 方法是
int main() {
HelperChild helperChild;
Child child(helperChild);
child.print();
return 0;
}
这会输出以下内容:
HelperChild
-- Base
HelperBase
为什么最后一行没有打印“HelperChild”?为了实现这一点,我需要做哪些更改?(我不确定我是否以正确的方式使用了virtual)。
编辑: 在我试图弄清楚的实际情况中,Base::print 是一个非常大的方法,我不想在 Child 类中覆盖它。我只是想改变帮助类的行为。
【问题讨论】:
-
HelperBase hb;是HelperBase,它不能包含HelperChild的实例。你需要了解对象切片
标签: c++ oop polymorphism