如何在C++中克隆对象?还是有其他解决方案

How to clone object in C++ ? Or Is there another solution?

本文关键字:解决方案 其他 对象 C++      更新时间:2023-10-16

我写了一个堆栈和队列实现(基于链表)。有一个堆栈(bigStack)。例如,我将bigStack分开(例如:stackAstackB )。我从bigStack pop()了一个节点,我在stackA push()。同样,我在stackB push().我希望bigStack不要改变。因此,我想克隆bigStack对象。如何在C++中克隆对象?或者我的问题有其他解决方案吗?

class Stack : public List {
public:
   Stack() {}
   Stack(const Stack& rhs) {}
   Stack& operator=(const Stack& rhs) {};
    ~Stack() {}
    int Top() {
        if (head == NULL) {
            cout << "Error: The stack is empty." << endl;
            return -1;
        } else {
            return head->nosu;
        }
    }
    void Push(int nosu, string adi, string soyadi, string bolumu) {
        InsertNode(0, nosu, adi, soyadi, bolumu);
    }
    int Pop() {
        if (head == NULL) {
            cout << "Error: The stack is empty." << endl;
            return -1;
        } else {
            int val = head->nosu;
            DeleteNode(val);
            return val;
        }
    }
    void DisplayStack(void);
};

然后。。。

Stack copyStack = veriYapilariDersi;
copyStack.DisplayStack();

典型的解决方案是编写自己的函数来克隆对象。 如果您能够提供复制构造函数和复制赋值运算符,这可能是您需要做的。

class Foo
{ 
public:
  Foo();
  Foo(const Foo& rhs) { /* copy construction from rhs*/ }
  Foo& operator=(const Foo& rhs) {};
};
// ...
Foo orig;
Foo copy = orig;  // clones orig if implemented correctly

有时,提供显式clone()方法是有益的,特别是对于多态类。

class Interface
{
public:
  virtual Interface* clone() const = 0;
};
class Foo : public Interface
{
public:
  Interface* clone() const { return new Foo(*this); }
};
class Bar : public Interface
{
public:
  Interface* clone() const { return new Bar(*this); }
};

Interface* my_foo = /* somehow construct either a Foo or a Bar */;
Interface* copy = my_foo->clone();

编辑:由于Stack没有成员变量,因此在复制构造函数或复制赋值运算符中无需执行任何操作即可从所谓的"右侧"(rhs)初始化Stack的成员。 但是,您仍然需要确保任何基类都有机会初始化成员。

您可以通过调用基类来执行此操作:

Stack(const Stack& rhs) 
: List(rhs)  // calls copy ctor of List class
{
}
Stack& operator=(const Stack& rhs) 
{
  List::operator=(rhs);
  return * this;
};

在C++中,复制对象意味着克隆。该语言中没有任何特殊的克隆。

正如标准所建议的那样,复制后,您应该拥有同一对象的 2 个相同副本。

有两种类型的复制:在未初始化的空间上创建对象时的复制构造函数和需要在设置新状态之前释放对象的旧状态(预期有效)的复制运算符。

如果你的对象不是多态的(堆栈实现可能不是),那么根据这里的其他答案,你想要的是复制构造函数。 请注意,C++中的复制构造和分配之间存在差异;如果你想要这两种行为(并且默认版本不符合你的需求),则必须实现这两个函数。

如果你的对象是多态的,那么切片可能是一个问题,你可能需要跳过一些额外的箍来做正确的复制。 有时人们使用称为clone()的虚拟方法作为多态复制的助手。

最后,请注意,如果您需要替换默认版本,则正确复制和分配实际上非常困难。 通常最好(通过 RAII)以这样的方式设置对象,即默认版本的复制/分配执行您希望它们执行的操作。 我强烈建议你看看迈耶的有效C++,尤其是第10,11,12项。


  #include<iostream>
  using namespace std;
  class A{
      public:
      int id;
      A():id(0){}
      A(A &o){
       
       
         this->id=o.id;
    
     }
    
     
};
int main()
{
    A obj;
    A obj2=obj;
    obj2.id=1;
    A *ho1 =new A();
    A *ho2=new A(*ho1);//while allocating, new memory allocation is done. it creates a deep copy clone.
   // A *ho2=ho1;// this does not allocate memory and created shall clone
    ho2->id=22;
    cout<<obj.id<<endl;
    cout<<obj2.id<<endl;
    cout<<ho1->id<<endl;
    cout<<ho2->id<<endl;
}

克隆是使用新建对象和常规对象创建为对象内存分配创建的。