为什么我得到一个输出"b(1) dc dvfunc"?

why I got an output 'b(1) dc dvfunc'?

本文关键字:dc dvfunc 输出 为什么 一个      更新时间:2023-10-16

我在这里的预期输出是"bc bvfunc b(1(dc dvfunc",但我得到了像"b(1?有人能帮我吗?谢谢你宝贵的时间!

#include<iostream>
using namespace std; 
class b {
 public:
  b() {
    cout<<" bc ";
    b::vfunc();
  }
  virtual void vfunc(){ cout<<" bvfunc "; }
  b(int i){ cout<<" b(1) "; }
};
class d : public b {
public:
  d(): b(1) {
    cout<<" dc ";
    d::vfunc();
  }
  void vfunc(){ cout<<" dvfunc"; }
};
main()
{
  d d;  
}

要获得所需的输出,您需要

d(){b(1);      //move b(1) from initializer list and put it in a constructor.  
    cout<<" dc ";

FYI initializer list用于在构造函数调用默认值之前initialize类的成员。构造函数可以覆盖这些值。

做事的顺序:

d((被调用。这将调用b(1(,然后调用构造函数的其余部分。

所以呼叫顺序是

b(1)
d() -> which is cout fc, and then cout dvfunc

b((从未被调用,因此它不会到达bvfunc。b((和b(int i(都是独立的构造函数,并且只调用其中一个,而不是两者。