【问题标题】:Copying polymorphic objects复制多态对象
【发布时间】:2017-09-21 12:17:00
【问题描述】:

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

#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 的复制?是不是因为我们用this 作为参数调用Derived 的复制构造函数?

如果我们确实调用了Derived的复制构造函数,那么为什么下面的代码编译不出来:

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

【问题讨论】:

  • ptrBase* 类型,为什么new Derived(ptr); 应该编译?
  • 复制构造函数,根据定义,复制同一类的实例。 ptr 不是同一类的实例。

标签: c++ oop polymorphism


【解决方案1】:

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

当然。 Derived::clone 中的 *this 表达式属于 Derived&amp; 类型,因此调用了 Derived::Derived(const Derived&amp; original) 复制构造函数。

为什么以下代码不能编译:

Base *b = new Derived(ptr);

此调用无法编译,因为ptr 是指针,而不是引用。这可以编译,但在克隆的上下文中是没有意义的:

Base *b = new Derived(*ptr);

克隆的关键在于你不知道你得到的结果是什么类型;当您执行 new Derived(*ptr) 时,您明确指定类型。

【讨论】:

    猜你喜欢
    • 2011-05-06
    • 2011-07-06
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 2014-12-06
    相关资源
    最近更新 更多