简体   繁体   English

为什么在C ++中一次调用基本方法

[英]Why is base method being called once overridden in C++

I have a situation similar to below (code is NOT exact, just to get my point across). 我的情况与下面类似(代码不准确,只是为了阐明我的意思)。 When I call DA() I expect the word "Desc" to be printed, but instead "Base" is printed. 当我调用DA()我希望打印"Desc"一词,但会打印"Base"

class Base {
public:
  void A() { B(); }
  virtual void B() { cout << "Base"; }
}

class Descendant : public Base {
public:
  virtual void B() overriden { cout << "Desc"; }
}

main () {
  Descendant D;
  D.A();
}

There must be something conceptual I'm missing here. 我在这里一定缺少一些概念上的东西。 Should DA() cause "Desc" to be printed? DA()是否应打印"Desc" If not, why? 如果没有,为什么?

There is an important error in the question. 这个问题有一个重要错误。 The method A is in fact the constructor of the Base class. 方法A实际上是Base类的构造函数。 And it makes sense that the constructor can't call any methods (even virtual) of derived classes since those derived classes don't exist yet. 而且有意义的是,构造函数不能调用派生类的任何方法(甚至是虚拟方法),因为这些派生类还不存在。

When A is a non-ctor, it works as expected. 当A是非ctor时,它将按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM