如何在C++中克隆对象?还是有另一种解决方案吗?

mer*_*ert 24 c++ queue stack data-structures

我写了一个Stack and Queue实现(基于Linked List).有一个堆栈(bigStack).例如,我分开bigStack(例如:stackAstackB).我pop()是一个节点bigStack,我push()stackA.以同样的方式,我push()stackB.我想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);

};
Run Code Online (Sandbox Code Playgroud)

然后...

Stack copyStack = veriYapilariDersi;
copyStack.DisplayStack();
Run Code Online (Sandbox Code Playgroud)

Joh*_*ing 32

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

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
Run Code Online (Sandbox Code Playgroud)

有时提供显式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();
Run Code Online (Sandbox Code Playgroud)

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

您可以通过调用基类来完成此操作:

Stack(const Stack& rhs) 
: List(rhs)  // calls copy ctor of List class
{
}

Stack& operator=(const Stack& rhs) 
{
  List::operator=(rhs);
  return * this;
};
Run Code Online (Sandbox Code Playgroud)