构造函数在虚拟继承中调用流?

时间:2017-11-07 14:49:21

标签: c++ inheritance constructor

#include<iostream>
using namespace std;

class A
{
 protected:
 int x;
 public:
 A(int i)
  { 
    x = i;
    cout<<"A parameterized constructor called x="<<x<<endl;
  }
 void print()
  {
    cout <<"A print function called x="<<x;
  }
};

class B: virtual public A
{
  public:
  B():A(10)
  {
    cout<<"B Constructor called"<<endl;
  }
};

class C: virtual public A 
{
  public:
  C():A(20)
  {
    cout<<"C Constructor called"<<endl;
  }
};

class D: public B, public C
{
  public:
  D():A(3)
  {
    cout<<"D parametrized constructor called"<<endl;
  }
};

int main()
{
  D d;
  d.print();
  getchar();
  return 0;
}
  

输出

A parameterized constructor called x=3
B Constructor called
C Constructor called
D parametrized constructor called
A print function called x=3

有人可以告诉我在上面的代码中首先调用了哪些构造函数?

根据输出,首先调用A&#39的参数构造函数但是如何知道在D中传递的值3? 它不应该采用默认值或调用默认构造函数而不是参数化构造函数吗?

0 个答案:

没有答案