【发布时间】: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