2017-09-21 54 views
3

我有一个关于复制多态对象的问题。我的出发点是如何实现克隆功能通常的例子:复制多态对象

#include <iostream> 

class Base 
{ 
    protected: 
    int a; 

    public: 
    void set_a(int x) { a = x; } 
    void get_a() { std::cout << a << "\n"; } 
    virtual ~Base() {} 

    virtual Base *clone() const = 0; 
}; 

class Derived : public Base 
{ 
    public: 
    virtual Derived *clone() const 
    { 
     return new Derived(*this); 
    } 
}; 

int main(int argc, char *argv[]) 
{ 
    Base *ptr = new Derived; 
    ptr->set_a(20); 
    ptr->get_a(); 

    Base *cpy = ptr->clone(); 
    cpy->get_a(); 
} 

为什么行new Derived(*this)导致this复印?是否因为我们将Derived的拷贝构造函数作为参数调用this

如果我们确实调用的Derived拷贝构造函数,那么为什么不将下面的编译:

Base *b = new Derived(ptr); //does not compile 
+2

'ptr'的类型是'Base *',为什么'new Derived(ptr);'应该编译? – songyuanyao

+2

根据定义,复制构造函数复制同一类的实例。 'ptr'不是同一个类的实例。 –

回答

4

是因为我们调用Derived拷贝构造函数?

绝对。 *thisDerived::clone中的表达式是Derived&,因此调用Derived::Derived(const Derived& original)复制构造函数。

为什么没有以下编译:

Base *b = new Derived(ptr); 

此调用不会编译,因为ptr是一个指针,而不是一个参考。这将编译,但它会在克隆的情况下没有意义:

Base *b = new Derived(*ptr); 

克隆的一点是,你不知道你会得到什么类型的结果;当你做new Derived(*ptr)你明确指定类型。