mmm*_*mmm 0 c++ polymorphism type-conversion polymorphic-associations
我需要复制构造一个对象,同时将它的类型更改为另一个类,它是同一个类层次结构的成员.我已经阅读过多态复制构造函数,并且(希望)理解它背后的想法.然而,我仍然不知道这种模式是否适用于我的情况,如果适用,如何实施它.我认为最好是在一个例子中展示我需要的东西.
有一Base类和两个子类,Child1和Child2.我需要创建一个Child2基于类型的对象Child1,即.最重要的是,我需要复制的对象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();
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,结果如下,即.没有类型转换:
Child1: 162611224:4 0
Child1: 162611272:4 1
Run Code Online (Sandbox Code Playgroud)
我究竟需要实施什么才能实现我的需求?我开始认为我需要实现一种类型转换机制而不是多态复制构造函数,但我已经很困惑了.
编辑:在这里要求跟进
最简单的解决方案可能是实现一个Child2带Child1&参数的构造函数.然后你可以简单地打电话:
Child2* c2 = new Child2(*c1);
Run Code Online (Sandbox Code Playgroud)