我需要帮助解决C ++中的特定编程问题(不确定这在C ++中是否可行)。我需要能够访问Base类中的所有公共成员函数,但是在分配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类。我想通过引用现有的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?
Derived类的内存分配或构造函数应该是什么样的?我想继承Base类的所有数据和成员函数,但不进行Base和Derived的“组合”数据分配。我试过重载operator new但没有运气。任何帮助表示赞赏。
答案 0 :(得分:0)
我不确定它是否符合您的要求,但您只需将Base
中存储的basePtr
内容复制到新Derived
对象中,然后删除{{ 1}}对象并使用旧的Base
指针指向新的Derived
对象。像这样:
Base
这样你最终只会得到一个对象(类型为Base *basePtr = new Base();
/* Do something with base here */
Derived *derivedPtr = new Derived(basePtr);
delete basePtr;
basePtr = derivedPtr;
derivedPtr = 0;
)并且不必存储指向它的单独指针,也不必存储Derived
对象,这看起来像你需要什么。
<强>更新强>
在我的情况下,我无法删除Base对象,因为我创建了数百万个(使用GigaBytes的RAM空间),人们可能正在使用指针/对这些对象的引用,因此将它们复制到Derived对象并删除旧对象基础对象对我不起作用。
在这种情况下,也许你应该尝试做一个“可扩展的*结构包装器。首先创建一个没有任何方法或成员的简单类:
Base
然后创建一个包装器结构:
class Additional{};
然后,不是从struct wrapper{
Base *basePtr;
Additional *moreInfo;
}
派生Derived
课程,而是从Base
派生。而不是存储数百万Additional
指针,存储数百万Base
指针。它会使你的代码变得更长,更难理解,但它会做你需要的。好吧 - 除非您的wrapper
类添加的唯一内容是指针或任何数量较小的数据。
如果Derived
中有virtual
个函数,为了将它们与新的层次结构一起使用,oyu只需要每次检查:
Base
答案 1 :(得分:0)
使用多重继承。
class Base()
class Derive1() : Base
class Derive2() : Base
class MostDerive() : Derive1 , Derive2
MostDerived()会很瘦。 Derive1和Derive2需要确定性地构建,但可以强加,或者可以使用一些Init()函数。