2015-01-14 60 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函數是複製多態對象的正確設計。

相關問題