创建派生类对象时将参数传递给基类构造函数

2021-12-30 00:00:00 oop constructor c++

考虑两个类 AB

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();
};

相关文章