Pass Parameter to Base Class Constructor while creating Derived class Object(创建派生类对象时将参数传递给基类构造函数)
问题描述
考虑两个类 A
和 B
class A
{
public:
A(int);
~A();
};
class B : public A
{
public:
B(int);
~B();
};
int main()
{
A* aobj;
B* bobj = new bobj(5);
}
现在B
类继承了A
.
我想创建一个B
的对象.我知道创建派生类对象也会调用基类构造函数,但这是没有任何参数的默认构造函数.
I want to create an object of B
. I am aware that creating a derived class object, will also invoke the base class constructor , but that is the default constructor without any parameters.
我想要的是 B
接受一个参数(比如 5),并将它传递给 A
的构造函数.请展示一些代码来演示这个概念.
What i want is that B
to take a parameter (say 5), and pass it on to the constructor of A
.
Please show some code to demonstrate this concept.
推荐答案
使用基成员初始化:
class B : public A
{
public:
B(int a) : A(a)
{
}
~B();
};
这篇关于创建派生类对象时将参数传递给基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:创建派生类对象时将参数传递给基类构造函数


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16