c++ - 为什么我得到输出 'b(1) dc dvfunc' ?

标签 c++

我在这里的预期输出是“bc bvfunc b(1) dc dvfunc”,但我得到的输出是“b(1) dc dvfunc”,为什么会这样?有人可以帮帮我吗?感谢您的宝贵时间!

#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 ";

仅供引用 initializer list 用于在构造函数调用默认值之前初始化类的成员。构造函数可以覆盖这些值。

关于c++ - 为什么我得到输出 'b(1) dc dvfunc' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15050522/

相关文章:

c++ - 模板类变量声明中的 "class VARIABLE"?

c++ - C++ 中的虚拟继承,孙子对象的大小很重?

c++ - 添加 vector

c++ - 相同的 printf 给出不同的结果

c++ - 对数组中的每个元素应用一个函数

c++ - while循环不循环

c++ - OpenSSL 错误 "assertion failed"

c++ - 如何向客户端重播 TCP 流

c++ - 无法从 'initializer-list' 转换为 UserController

c++ - 在 C++ 中获取 iPhone 目录路径