为什么我继承的构造函数调用我的基本默认构造函数

Why my inherited constructor call my base default constructor

本文关键字:我的 默认 构造函数 函数调用 继承 为什么      更新时间:2023-10-16

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

例:

答.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 . . .

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

相关文章: