如何在 C++ 中克隆对象?或者有其他解决方案吗?
我写了一个堆栈和队列实现(基于链表).有一个堆栈(bigStack
).例如,我将 bigStack
分开(例如:stackA
和 stackB
).我 pop()
一个来自 bigStack
的节点,我 push()
在 stackA
中.同样,我在stackB
中push()
.我希望 bigStack
不会改变.因此我想克隆 bigStack
对象.如何在 C++ 中克隆对象?或者我的问题还有其他解决方案吗?
I wrote a Stack and Queue implementation (Linked List based). There is one stack (bigStack
). For example, I separate bigStack
(example: stackA
and stackB
). I pop()
a node from bigStack
, I push()
in stackA
. In the same way, I push()
in stackB
. I want bigStack
to not change. Therefore I want to clone the bigStack
object. How do I clone objects in C++? Or is there another solution to my problem?
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();
推荐答案
对此的典型解决方案是编写自己的函数来克隆对象.如果您能够提供复制构造函数和复制赋值运算符,这可能是您需要的.
The typical solution to this is to write your own function to clone an object. If you are able to provide copy constructors and copy assignement operators, this may be as far as you need to go.
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()
方法是有益的,尤其是对于多态类.
Sometimes it is beneficial to provide an explicit clone()
method, especially for polymorphic classes.
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
).但是,您仍然需要确保任何基类都有机会初始化它们的 成员.
Since Stack
has no member variables, there's nothing to do in the copy constructor or copy assignment operator to initialize Stack
's members from the so-called "right hand side" (rhs
). However, you still need to ensure that any base classes are given the opportunity to initialize their members.
您可以通过调用基类来实现:
You do this by calling the base class:
Stack(const Stack& rhs)
: List(rhs) // calls copy ctor of List class
{
}
Stack& operator=(const Stack& rhs)
{
List::operator=(rhs);
return * this;
};
相关文章