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++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01