Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 复制多态对象_C++_Oop_Polymorphism - Fatal编程技术网

C++ 复制多态对象

C++ 复制多态对象,c++,oop,polymorphism,C++,Oop,Polymorphism,我有一个关于复制多态对象的问题。我的出发点是如何实现克隆功能的常见示例: #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(

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

#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();
}
是因为我们调用了
派生的
的复制构造函数吗

当然
*此
派生::克隆中的
表达式属于
派生类型&
,因此调用
派生::派生(常量派生和原始)
复制构造函数

为什么不编译以下文件:

Base *b = new Derived(ptr); //does not compile
Base *b = new Derived(ptr);
此调用无法编译,因为
ptr
是指针,而不是引用。这可以编译,但在克隆环境中毫无意义:

Base *b = new Derived(*ptr);

克隆的意义在于你不知道结果是什么类型的;当您执行
new-Derived(*ptr)
时,您需要明确指定类型。

ptr
属于
Base*
类型,为什么
new-Derived(ptr)应该编译?根据定义,复制构造函数复制同一类的实例<代码>ptr
不是同一类的实例。