相关疑难解决方法(0)

在C++中复制多态对象

我有Base派生的基类Derived1,Derived2Derived3.

我为其中一个派生类构建了一个实例,我将其存储为Base* a.我现在需要制作一个我将存储的对象的深层副本Base* b.

据我所知,复制类的正常方法是使用复制构造函数并重载operator=.但是,因为我不知道是否a是类型Derived1,Derived2或者Derived3,我想不出使用复制构造函数的方法operator=.我能想到的唯一方法是干净利落地完成这项工作:

class Base
{
public:
  virtual Base* Clone() = 0;

};
Run Code Online (Sandbox Code Playgroud)

Clone派生类中的实现如下:

class Derivedn : public Base
{
public:
  Base* Clone() 
  {
    Derived1* ret = new Derived1;
    copy all the data members
  }
};
Run Code Online (Sandbox Code Playgroud)

Java倾向于使用Clone相当多的C++方式更多吗?

c++ clone

35
推荐指数
1
解决办法
1万
查看次数

在没有动态内存分配的情况下,C++中是否有一种机制可以从基类指针生成派生类的完整副本?

请考虑以下示例,其中在取消引用基指针期间发生对象切片.

#include <stdio.h>

class Base {
  public:
    virtual void hello() {
        printf("hello world from base\n");
    }
};
class Derived : public Base{
  public:
    virtual void hello() {
        printf("hello world from derived\n");
    }
};

int main(){
    Base * ptrToDerived = new Derived;
    auto d = *ptrToDerived;
    d.hello();
}
Run Code Online (Sandbox Code Playgroud)

我希望变量d保存类型的对象Derived而不是类型的对象Base,没有动态内存分配,也没有显式强制转换.

我已经看过这个问题了,但是答案中提出的解决方案需要动态内存分配,因为它返回一个指向新对象的指针,而不是新对象的值.

这在C++ 11中是否可行?

c++ pointers auto c++11

4
推荐指数
1
解决办法
123
查看次数

标签 统计

c++ ×2

auto ×1

c++11 ×1

clone ×1

pointers ×1