0

My expected output here was " bc bvfunc b(1) dc dvfunc", but I got an output like "b(1) dc dvfunc" why is it so? Could somebody help me out? thanks for your precious time!

#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;  
}
4

2 に答える 2

1

The order in which things are done:

d() is called. This calls b(1), and then the rest of the constructor.

So the call order is

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

b() is never called, so it will not reach bvfunc. both b() and b(int i) are stand-alone constructors, and only one will be called, not both.

于 2013-02-24T09:52:37.997 に答える
1

必要な出力を得るには

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

FYIinitializer listは、コンストラクターがデフォルト値を呼び出す前にクラスのメンバーに使用されinitializeます。コンストラクターはこれらの値を上書きできます。

于 2013-02-24T09:57:30.497 に答える