【问题标题】:Why my inherited constructor call my base default constructor [duplicate]为什么我继承的构造函数调用我的基本默认构造函数[重复]
【发布时间】:2018-03-28 00:41:06
【问题描述】:

也许我只是向 Google 提出了很糟糕的问题,但我找不到我的问题的答案。我的麻烦是我继承的构造函数调用了我的默认基本构造函数,我真的不明白为什么。这是我的简化版。

例子:

A.cpp

#include <iostream>
#include "A.h"

using namespace std;

A::A()
{
    cout << "A" << endl;
}

B.cpp

#include <iostream>
#include "B.h"

using namespace std;

B::B()
{
    cout << "B" << endl;
}

B::B(int x)
{
    cout << "B" << x << endl;
}

源.cpp

#include <iostream>
#include "A.h"
#include "B.h"

using namespace std;

int main() {
    B * b = new B();
    cout << "---" << endl;
    B * b2 = new B(2);

    system("PAUSE");
    return 0;
}

输出:

A
B
---
A
B2
Press any key to continue . . .

我只是想看看 B 构造函数做了什么。像这样:

B
---
B2
Press any key to continue . . .

【问题讨论】:

  • 你那里有继承的构造函数吗?此外,要成功构建B 类型的对象,您还需要调用A 的ctor...
  • 听起来你应该重新审视good C++ book 你总是必须构造派生类的基础部分。
  • 你没有显示你的类的定义,你也没有直接声明B 派生自A。我想我们可以从问题的标题和提供的输出中推断出继承。
  • 您没有显示一些重要的代码。见minimal reproducible example。我的猜测是您在B.h 中写了class B : A {,这意味着“B 是A”,这意味着要创建B,您还必须有一个需要构造的A。跨度>
  • #pragma once #include "A.h" class B : public A { public: B(); B(整数); 〜B(); };

标签: c++ inheritance constructor


【解决方案1】:

因为父类可能负责例如初始化子类稍后依赖的成员变量(包括可能分配的内存)。

【讨论】:

  • 构造函数不会分配初始化当前对象的存储空间。您的意思只是通过初始化成员变量来概括。
猜你喜欢
  • 2016-03-24
  • 1970-01-01
  • 2011-05-20
  • 1970-01-01
  • 2016-12-05
  • 2012-04-12
  • 2015-10-18
  • 1970-01-01
相关资源
最近更新 更多