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();
};
这篇关于创建派生类对象时将参数传递给基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:创建派生类对象时将参数传递给基类构造函数


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01