相关疑难解决方法(0)

我可以将指针传递给超类,但是可以创建一个子类的副本吗?

我有一个函数,它获取指向超类的指针并对其执行操作.但是,在某些时候,该函数必须对输入的对象进行深度复制.有什么方法可以执行这样的副本吗?

我想到让函数成为模板函数并让用户传递类型,但我希望C++提供更优雅的解决方案.

c++ polymorphism copy-constructor

3
推荐指数
1
解决办法
439
查看次数

创建不使用虚拟基类的对象的克隆

#include<iostream>
using namespace std;

class Something
{
  public:
  int j;
  Something():j(20) {cout<<"Something initialized. j="<<j<<endl;}
};

class Base
{
  private:
    Base(const Base&) {}
  public:
    Base() {}
    virtual Base *clone() { return new Base(*this); }
    virtual void ID() { cout<<"BASE"<<endl; }
};

class Derived : public Base
{
  private:
    int id;
    Something *s;
    Derived(const Derived&) {}
  public:
    Derived():id(10) {cout<<"Called constructor and allocated id"<<endl;s=new Something();}
    ~Derived() {delete s;}
    virtual Base *clone() { return new Derived(*this); }
    virtual void ID() { cout<<"DERIVED id="<<id<<endl; } …
Run Code Online (Sandbox Code Playgroud)

c++ virtual deep-copy shallow-copy

0
推荐指数
1
解决办法
895
查看次数