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
'ptr'的类型是'Base *',为什么'new Derived(ptr);'应该编译? – songyuanyao
根据定义,复制构造函数复制同一类的实例。 'ptr'不是同一个类的实例。 –