我编写了一个堆栈和队列实现(基于链表)。有一个栈(bigStack
)。比如我分开bigStack
(例子:stackA
and stackB
). I pop()
一个节点来自bigStack
, I push()
in stackA
。以同样的方式,我push()
in 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);
};
then...
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
没有成员变量,在复制构造函数或复制赋值运算符中无需执行任何初始化操作Stack
来自所谓“右手边”的成员(rhs
)。但是,您仍然需要确保任何基类都有机会进行初始化their成员。
您可以通过调用基类来完成此操作:
Stack(const Stack& rhs)
: List(rhs) // calls copy ctor of List class
{
}
Stack& operator=(const Stack& rhs)
{
List::operator=(rhs);
return * this;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)