【发布时间】:2011-10-14 08:54:44
【问题描述】:
我需要复制构造一个对象,同时将其类型更改为另一个类,该类是同一类层次结构的成员。我已经阅读了多态复制构造函数,并且(希望)理解它背后的想法。然而,我仍然不知道这种模式是否适用于我的情况,如果适用,如何实现它。我认为最好在示例中展示我需要的内容。
有一个Base 类和两个子类Child1 和Child2。我需要基于Child1 创建一个Child2 类型的对象,即。最重要的是,我需要将p_int 指向的对象从Child1 复制到Child2。我写了一个简单的程序来说明它:
#include <iostream>
using namespace std;
class Base {
public:
Base() { p_int = new int; *p_int = 0; }
~Base() { delete p_int; }
virtual Base* clone() const = 0;
void setpInt(int val) { *p_int = val; }
void setInt(int val) { a = val; }
virtual void print() {
cout << "Base: ";
cout << (long)p_int << ":" << *p_int << " " << a << endl;
}
protected:
int* p_int;
int a;
};
class Child1 : public Base {
public:
Child1() {};
Child1(const Child1& child) {
p_int = new int (*child.p_int);
a = child.a + 1;
}
Base* clone() const { return new Child1(*this); }
void print() {
cout << "Child1: ";
cout << (long)p_int << ":" << *p_int << " " << a << endl;
}
};
class Child2 : public Base {
public:
Child2() {};
Child2(const Child2& child) {
p_int = new int (*child.p_int);
a = child.a + 1;
}
Base* clone() const { return new Child2(*this); }
void print() {
cout << "Child2: ";
cout << (long)p_int << ":" << *p_int << " " << a << endl;
}
};
int main() {
Child1* c1 = new Child1();
Child2* c2;
c1->setpInt(4);
c1->print();
c2 = (Child2*)c1->clone();
c2->print();
}
不幸的是,结果如下,即。没有类型转换:
Child1: 162611224:4 0
Child1: 162611272:4 1
我究竟需要实现什么才能实现我的需要?我开始认为我需要实现一种类型转换机制而不是多态复制构造函数,但我已经很困惑了。
编辑:要求跟进here
【问题讨论】:
-
您的代码会产生内存泄漏:在派生类的复制构造函数中,您分配新内存并将其地址分配给 p_int,而不会释放先前在
Base的默认构造函数中分配的内存。跨度> -
是吗?我认为虚拟 Base 类的析构函数会释放为 Child1.p_int 保留的内存,不是吗?
-
是的,虚拟析构函数将释放
p_int指向的内存,但是你分配了两次(一次在Base的构造函数中,一次在Child的构造函数中)并且只释放一次(在析构函数中)。您需要做的是提供由p_int参数化的Base构造函数(也可能是a),以便派生类可以提供自己的值:class Base { protected: Base(int * inp_int, int ina) : p_int(inp_int), a(ina) {} ... }; class Child1 : public Base { public: Child1(Child1 const & child) : Base(new int (*child.p_int), child.a + 1) {} ... };。 -
派生类需要直接访问基类的数据成员有点奇怪,也许您可以检查您的设计以获得更好的封装(如果
Base包含这些数据成员,它应该负责它们的管理;如果对这些数据的所有操作都是由派生类执行的,那么它可能应该移到那里。每个类的职责都应该明确定义)。 -
该示例仅显示了我遇到问题的一段代码,而不是实际
Base类将具有的全部功能。当然,它会使用p_int。
标签: c++ polymorphism type-conversion polymorphic-associations