创建不与虚拟基类一起使用的对象的克隆
#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; }
void assignID(int i) {id=i;}
};
int main()
{
Base* b=new Derived();
b->ID();
Base* c=b->clone();
c->ID();
}//main
关于运行:
Called constructor and allocated id
Something initialized. j=20
DERIVED id=10
DERIVED id=0
在第一个链接中,Space_C0wb0y 说
“由于克隆方法是一种方法 对象的实际类,它可以 还创建一个深层副本。它可以访问 它所属类的所有成员 到,所以没有问题。”
我不明白如何发生深复制。在上面的程序中,甚至没有发生浅复制。即使基类是抽象类,我也需要它工作 我怎样才能在这里进行深复制?
#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; }
void assignID(int i) {id=i;}
};
int main()
{
Base* b=new Derived();
b->ID();
Base* c=b->clone();
c->ID();
}//main
On running:
Called constructor and allocated id
Something initialized. j=20
DERIVED id=10
DERIVED id=0
My question is related to this, this and this post.
In the first link, Space_C0wb0y says
"Since the clone-method is a method of
the actual class of the object, it can
also create a deep-copy. It can access
all members of the class it belongs
to, so no problems there."
I don't understand how a deep copy can happen. In the program above, not even a shallow copy is happening. I need it to work even if the Base class is an abstract class. How can I do a deep copy here? Help please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,您的复制构造函数不执行任何操作,因此您的克隆方法不执行任何复制操作。
请参见行
Derived(const Derived&) {}
编辑:如果您添加代码来通过赋值复制 Derived 的所有成员,它将成为浅表副本。如果您还复制(通过创建新实例)您的 Something 实例,它将成为深层复制。
Well, your copy constructor does nothing, so your clone method does nothing in the way of copying.
See line
Derived(const Derived&) {}
EDIT: if you add code to copy by assignment all members of Derived, it will become a shallow copy. If you also copy (by making a new instance) your instance of Something, it will become a deep copy.