为什么构造函数忽略重写的虚函数
Why do constructors ignore overriden virtual functions?
下面是一个例子:
struct parent {
int a;
virtual void stuff() { a = 5; } //variant A
void roundabout() { stuff(); }
parent() { stuff(); }
};
struct child : parent {
void stuff() override { a = 6; } //variant B
child() : parent() {}
};
和用法
child c; //calls variant A
auto p = reinterpret_cast<parent*>(&c);
c.stuff(); //calls variant B
c.roundabout(); //calls variant B
p->stuff(); //calls variant B
p->roundabout() //calls variant B
所以在构造之后,我从类内部或外部调用 stuff() 的任何方式,都没有明确说明 parent::stuff() 我得到了 child::stuff(),正如预期的那样。
一个例外是父构造函数仍然调用 parent::stuff(),即使它由子构造函数触发。这真的很烦人,因为我必须在构造函数调用的函数中包含额外的逻辑,以使它们按预期运行。为什么会这样?
除非父实例已存在,否则子项的实例不能存在。因此,在父级的构造函数中,不能存在子项的实例。那么,如果没有孩子存在,你怎么能打电话给child::stuff
呢?
相关文章:
- 在 C++ 中用派生类型重写成员函数
- 重写虚拟函数和继承
- C++调用使用重写函数的父类函数
- 重写打印函数而不是覆盖基类
- 重写函数不打印基类数据
- 将一个小的 C 定义重写为"normal" C++函数
- 重写另一个方法 [C++] 使用的超类回调函数
- 具有派生参数的函数重写
- 在回调中使用函数时,C++未知重写说明符
- 用模板化函数重写虚拟函数
- 没有函数重写的多重继承.为什么模棱两可
- C++ 继承构造函数重写
- 关于C++中的虚拟函数重写
- C++函数重写不起作用
- 如何实现类变量的虚拟函数重写
- 将C++函数重写为C#(将指针传递到数组中的下一个元素)
- 引用可以用于实现函数重写吗
- 用函数重写嵌套的if-else语句
- C++继承函数重写
- 本机C++中的函数重写