2015-01-14 27 views
1

有没有办法通过指向基地复制派生类对象? 或者如何创建这样一个复制构造函数?有没有办法通过一个指向基地的派生类对象?

例如:

class Base { 
public: Base(int x) : x(x) {} 
private: int x; 
}; 

class Derived1 : public Base { 
public: 
Derived(int z, float f) : Base(z), f(f) {} 
private: 
float f; 
}; 

class Derived2 : public Base { 
public: 
Derived(int z, string f) : Base(z), f(f) {} 
private: 
string f; 
}; 

void main() 
{ 
Base * A = new *Base[2]; 
Base * B = new *Base[2]; 
A[0] = new Derived1(5,7); 
A[1] = new Derived2(5,"Hello"); 
B[0] = Base(*A[0]); 
B[1] = Base(*A[1]); 
} 

问题在于是否* B [0]将是一个Derived1对象和* B [1]一个Derived2的对象? 如果不是,我怎么能通过指向基类的指针复制派生类?是否有通过基类或派生类构建复制构造函数的特定方法?默认的复制构造函数是否足够用于该示例?

+0

查找[* clone pattern *](https://katyscode.wordpress.com/2013/08/22/c-polymorphic-cloning-and-the-crtp-curiously-recurring-template-pattern/)。 – Quentin

+1

是'Base * A = new * Base [2];'一个错字?这不会编译。实际上,你的整个main()方法充满了问题。 – mbgda

+0

我认为多态副本通过一种名为'Clone()'的方法来实现(你必须自己编写克隆方法),并且基本上按照构造函数的方式编写它,但正如@Quentin所说,查找克隆具体模式。 – YoungJohn

回答

5

您可以对提供虚拟方法Clone

class Base { 
public: 
    Base(int x) : x(x) {} 
    virtual ~Base() {} 
    virtual Base* Clone() const { return new Base(*this); } 
private: 
    int x; 
}; 

class Derived1 : public Base { 
public: 
    Derived1(int z, float f) : Base(z), f(f) {} 
    virtual Derived1* Clone() const { return new Derived1(*this); } 
private: 
    float f; 
}; 

class Derived2 : public Base { 
public: 
    Derived2(int z, std::string f) : Base(z), f(f) {} 
    virtual Derived2* Clone() const { return new Derived2(*this); } 
private: 
    std::string f; 
}; 
0

在你构建类Base的两个实例,你main(除了错字)的第二行,然后你问,如果以某种方式在最后两行这些对象将在运行中变形并成为派生类的实例。那当然是不可能的。

此外,请检查此answer

注意:我只是评论你提供的代码和用例。使用虚拟Clone函数是复制多态对象的正确设计。

相关问题