c++ - 基类属性的不同初始化

标签 c++ inheritance constructor

考虑一个具有属性的基类

class Base 
{
  protected:

  AttributeBase * elementPtr;
  ...
};

还有一个派生类

class Derived : public Base
{
  ...
};

我还有一个类 AttributeDerived 派生自 AttributeBase

当我创建类 Base 的对象时,我希望 elementPtr 以这种方式初始化:

elementPtr = new AttributeBase()

但是当我创建类 Derived 的对象时,我希望 elementPtr 以这种方式初始化:

elementPtr = new AttributeDerived()

最干净的方法是什么?

最佳答案

您可以向 Base 添加一个 protected 构造函数,它允许派生类传递 elementPtr 以使用:

Base (AttributeBase* elementPtr) : elementPtr(elementPtr)
{}

然后在您的派生类中,调用该构造函数:

Derived() : Base(new AttributeDerived())
{}

如果您使用 C++11,则可以让其他 Base 构造函数委托(delegate)给 protected 构造函数以限制代码重复。

关于c++ - 基类属性的不同初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31983470/

相关文章:

c++ - 编写多个 If 语句的优雅方式

c++ - 混合使用纯虚方法和虚方法的类

c# - 派生类中存在重写和隐藏方法。为什么?

c++ - 显式构造函数中的类型推断

c++ - 为什么将 std::move(object) 和此对象的成员传递给函数会导致 SIGSEGV

c++ - 如何从用户输入中读取不同的数字? C++

c++ - 带有静态库 : linker throws 'undefined reference' all the time 的 Android NDK

android - 如何覆盖xml中的默认背景颜色?

c++ - C++ 中的对象构建

c++ - 在 map 中存储结构;检查 map 中是否存在结构