在创建Derived类Object时将参数传递给基类构造函数 [英] Pass Parameter to Base Class Constructor while creating Derived class Object

查看:108
本文介绍了在创建Derived类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 inherits A

Now the class B inherits 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();
};

这篇关于在创建Derived类Object时将参数传递给基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆