具有类型转换的多形复制构造函数

具有类型转换的多形复制构造函数

本文介绍了具有类型转换的多形复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要复制构造一个对象,同时将它的类型改变为另一个类,它是同一个类层次结构的成员。我已经阅读关于多态复制构造函数和(希望)了解其背后的想法。然而,我仍然不知道这种模式是否适用于我的情况,如果是这样,如何实现它。

I need to copy-construct an object simultaneously changing it's type to another class being a member of the same class-hierarchy. I've read about polymorphic copy-constructors and (hopefully) understand the idea behind it. Yet, I still don't know if this pattern applies to my case and, if so, how to implement it. I think it's best if I show what I need on an example.

有一个 Base 类和两个孩子类, Child1 Child2 。我需要创建一个类型 Child2 基于 Child1 ,即。最重要的是,我需要复制 p_int 指向从 Child1 Child2 。我写了一个简单的程序来说明它:

There is a Base class and two child classes, Child1 and Child2. I need to create an object of type Child2 basing on Child1, ie. most of all, I need to copy the object p_int is pointing to from Child1 to Child2. I've written a simple program to illustrate it:

#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

我需要实现什么,才能实现我需要的?我开始认为有一个类型转换机制我需要实现,而不是一个多态复制构造函数,但我很困惑已经。

What exactly do I need to implement, to be able to achieve what I need? I'm starting to think there is a type-conversion mechanism I need to implement rather than a polymorphic copy-constructor, but I'm confused already.

EDIT:请求

推荐答案

最简单的解决方案可能是实现 Child2 > Child1& 作为参数。那么你可以简单地调用:

Simplest solution would probably be to implement a Child2 constructor taking a Child1& as parameter. Then you could simply call:

Child2* c2 = new Child2(*c1);

这篇关于具有类型转换的多形复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:22