直接复制与虚拟复制构造函数(克隆函数)
我试图了解为什么我们需要克隆功能(虚拟复制构造函数)已经两天了。
我创建了一个简单的示例(下面的代码)::
#include <iostream>
class Dog
{
public:
Dog() { std::cout << "I am a Dog\n"; }
virtual Dog* clone() { return new Dog(*this); }
virtual void info() { std::cout << "info : I am a Dog\n";}
};
class RedDog : public Dog
{
public:
RedDog() {std::cout << "I am a RedDog\n"; }
RedDog* clone() { return new RedDog(*this); }
void info() { std::cout << "info : I am a RedDog\n"; }
};
void foo(Dog* pd)
{
Dog* temp = pd;
//Dog* temp = pd->clone();
temp->info();
}
int main()
{
Dog d;
std::cout << "########################\n";
RedDog rd;
std::cout << "########################\n";
foo(&rd);
return 0;
}
在FOO函数中使用克隆与使用普通副本之间没有区别。 它将执行适当对象的功能。
请在一个简单的示例中向我展示,如果我不使用克隆,会出现问题或使用克隆。
谢谢
It has been two days I'm trying to understand why do we need clone function( virtual copy constructor).
I created a simple example (code below): :
#include <iostream>
class Dog
{
public:
Dog() { std::cout << "I am a Dog\n"; }
virtual Dog* clone() { return new Dog(*this); }
virtual void info() { std::cout << "info : I am a Dog\n";}
};
class RedDog : public Dog
{
public:
RedDog() {std::cout << "I am a RedDog\n"; }
RedDog* clone() { return new RedDog(*this); }
void info() { std::cout << "info : I am a RedDog\n"; }
};
void foo(Dog* pd)
{
Dog* temp = pd;
//Dog* temp = pd->clone();
temp->info();
}
int main()
{
Dog d;
std::cout << "########################\n";
RedDog rd;
std::cout << "########################\n";
foo(&rd);
return 0;
}
There is no difference between using clone in foo function and using normal copy.
it will execute the function of appropriate object.
Please show me in an example simple that if I don't use clone there will be problem, or usage of clone.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
克隆功能与工厂一起使用。这些提供了一个基于给定输入的对象。实现是要将地图枚举链接到每个所需的对象,称为基类。因此,如果您的输入指定红色狗,则可以调用函数
dog* getDog(enumdog newdog)
,如果之前将其提供给地图,则为您提供所需的对象。一个替代方案是所有枚举的开关案例。
The clone function is used with factories. These provide an object based on given input. An implementation is to have a map enums linked to each needed object known as the base class. So if your input specifies a red dog, you call the function
Dog* getDog(enumDog newDog)
and it gives you your needed object if it was provided to the map before.An alternative for this is switch-case with all the enums.