使用 "new" 为派生类分配内存时,如何调用 Base 构造函数?
when using "new" to allocate memory to a Derived class, how to call the Base constructor?
我使用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;
}
};
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 函数何时会在c++中包含stack_Unwind_Resume调用
- Singleton模式中的手动析构函数调用:调用多次
- 从同一父调用调用不同的子类函数
- 我可以通过CPP程序中的数据库调用调用Java程序
- C++17标准对在nullptr上调用delete有何规定
- NSIS系统::调用-调用方法失败
- 参数构造函数调用调用
- 当 int 方法工作正常时,void 方法有何不同,或者为什么我不能调用 void 方法?
- 让非托管 C++ 代码调用调用 C# 代码的托管 C++ 代码
- 关于在矢量上调用clear如何改变容量,标准有何规定
- 如何让函数调用调用它的函数
- 如何p/调用调用函数只使用,但c++需要.a/.lib/.o文件
- C#DLL可以调用调用本机C++静态库的C++/CLI托管包装器吗