c++ - 分配派生类时使用现有的基类对象

标签 c++ inheritance memory allocation

我需要帮助解决 C++ 中的特定编程问题(不确定这在 C++ 中是否可行)。我需要能够访问 Base 类中的所有公共(public)成员函数,但不想在分配 Derived 类对象时为 Base 类数据分配内存。

比方说,我有:

class Base
{
  public:
    Base();
    ~Base();
    int GetFoo() { return foo; }
    // other public member functions of Base class

  private:
    int foo;
    // other data
};

class Derived : public Base
{
  public:
    Derived(Base *BasePtr);
    Derived(Base &BaseRef);
    ~Derived();
    double GetXyz() { return xyz; }
    // other public member functions of Derived class

  private:
    double xyz;
    // other data
};

现在,假设我已经分配并初始化了一个基类。我想通过引用现有的 Base 对象来创建一个新的 Derived 类对象,并仅为 Derived 类的特定数据分配内存。按照上面的例子,我已经为 Base 类对象中的“int foo”分配了内存,而只想为 Derived 类对象中的“double xyz”分配内存。

Base *basePtr = new Base();
Derived *derivedPtr = new Derived(basePtr); // what is the content of this function?

派生类的内存分配或构造函数应该是什么样的?我想继承 Base 类的所有数据和成员函数,但不对 Base 和 Derived 进行“组合”数据分配。我试过重载 operator new 但没有成功。感谢您的帮助。

最佳答案

我不确定它是否符合您的要求,但您可以简单地将存储在 basePtr 中的 Base 的内容复制到一个新的 Derived 对象,然后删除 Base 对象并用旧的 Base 指针指向新的 Derived 对象。像这样:

Base *basePtr = new Base();
/* Do something with base here */
Derived *derivedPtr = new Derived(basePtr);
delete basePtr;
basePtr = derivedPtr;
derivedPtr = 0;

这样一来,您最终只会得到一个对象(Derived 类型),而不必存储指向它的单独指针,也不必存储 Base对象,这似乎正是您所需要的。

更新:

in my case, I cannot delete the Base object since I would have created millions of them (using GigaBytes of RAM space) and people could be using pointers/references to those objects, so copying them to Derived objects and deleting the old Base objects doesn't work for me.

在那种情况下,也许你应该尝试做一个“可扩展的*结构包装器。首先创建一个没有任何方法或成员的简单类:

class Additional{};

然后创建一个包装器结构:

struct wrapper{
    Base *basePtr;
    Additional *moreInfo;
}

然后,不是从 Base 派生您的 Derived 类,而是从 Additional 派生它。而不是存储数百万个 Base 指针,而是存储数百万个 wrapper 指针。它会使您的代码变得更长且更难理解,但它会满足您的需求。嗯 - 除非你的 Derived 类添加的唯一东西是指针或任何占用较小大小的数据。

如果你在 Base 中有 virtual 函数,为了在新的层次结构中使用它们,你只需要每次检查:

wrapper *wrapperPtr = &alreadyCreatedSomewhereWrapper;
if(wrapperPtr->moreInfo)
    wrapperPtr->moreInfo->function();
else
    wrapperPtr->basePtr->function();

关于c++ - 分配派生类时使用现有的基类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20013270/

相关文章:

C++类名注入(inject)

c++ - 如何传递这种类型的自动功能?

c - 应该始终使用 memcpy 吗?

c# - 我如何更改此代码,以便它改为写入字符串?

Python Tkinter - 如何使某些代码使用更少的内存

c++ - 将修改后的矩阵中的所有数字相加

c++ - 现在允许为 std::string 分配一个数字吗?

css - 防止子元素使用父类

c++ - 如果使用基指针声明,为什么简单析构函数不删除派生对象

javascript - mixins 中的 prototype.js 实例属性