使用 "new" 为派生类分配内存时,如何调用 Base 构造函数?

when using "new" to allocate memory to a Derived class, how to call the Base constructor?

本文关键字:何调用 调用 Base 构造函数 派生 new 分配 内存 使用      更新时间:2023-10-16

我使用new分配内存到派生类,我还想初始化它的基私有成员

我该怎么做呢?

class Base {
private:
  int value;
}
class Derived : public Base {
  ....
}

是否有使用基构造函数的聪明方法?谢谢!

Base需要有一个初始化value的构造函数,例如

Base(int v):value(v){};

然后,在Derived构造函数中,调用Base构造函数作为

Derived(int v):Base(v){...};

无论是否显式调用,基类的构造函数总是在调用大多数派生类的构造函数之前调用。默认情况下,调用默认构造函数。如果你想要一些其他的行为,你可以在初始化列表中做:

class Base { 
protected:
    explicit Base(int) {}
};
class Derived : public Base {
public:
    Derived() : Base(42)  // <-- call to base constructor
    { }
};

你可以让驱动类成为基类的友类

class Base
{
friend class Drived;
private:
    int a;
};
class Drived :public Base
{
public:
    Drived(){
        this->a=23;
    }
};

或者使基类的变量受保护:

class Base
{
protected:
    int a;
};
class Drived :public Base
{
public:
    Drived(){
        this->a=23;
    }
};