【发布时间】:2013-11-29 13:34:45
【问题描述】:
我需要 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 对象来创建一个新的 Derived 类对象,并仅为 Derived 类特定的数据分配内存。按照上面的例子,我已经为基类对象中的“int foo”分配了内存,只想为派生类对象中的“double xyz”分配内存。
Base *basePtr = new Base();
Derived *derivedPtr = new Derived(basePtr); // what is the content of this function?
Derived 类的内存分配或构造函数应该是什么样的?我想继承 Base 类的所有数据和成员函数,但不做 Base 和 Derived 的“组合”数据分配。我试过重载 operator new 但没有运气。任何帮助表示赞赏。
【问题讨论】:
-
您可能需要一个复制构造函数,或者不创建基类对象,而是在派生类中调用基类的构造函数
-
请参阅下面我对答案 1 的评论,我无法选择不预先创建 Base 对象。
标签: c++ inheritance memory allocation