在c++中什么情况下使用克隆,以及如何使用它
Which situation will use clone in C++ and how to use it?
虚拟克隆和克隆有什么区别?我找到下面的例子,它克隆派生到基,它是干什么用的?
class Base{
public:
virtual Base* clone() {return new Base(*this);}
int value;
virtual void printme()
{
printf("love mandy %dn", value);
}
};
class Derived : public Base
{
public:
Base* clone() {return new Derived(*this);}
virtual void printme()
{
printf("derived love mandy %dn", value);
}
};
Derived der;
der.value = 3;
Base* bas = der.clone();
bas->printme();
考虑一下:
Base * b = get_a_base_object_somehow();
//现在,b的类型可以是Base,派生的,或者是从Base派生的
Base * c = b->clone();
//现在,c和b的类型是一样的,你可以在不知道它的类型的情况下复制它。
考虑一下:
Base* p1 = &der;
Base* p2 = p1->clone()
p2->printme();
如果clone()
不是虚拟的,结果将是"love mandy 3"。如果是虚拟的,结果将是"derived love mandy 3"。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 为什么使用 "this" 指针调用派生成员函数?
- 使用新行和不使用新行读取文件
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 如何确定我已使用非编码文件到达 EOF?
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 使用CMake创建QML插件
- 使用 LLVM 的 libc++ 时,__1 符号从何而来?
- 在std::cout之后使用std::cin时,换行符从何而来
- 为什么以及在何处在C++中使用引用和指针
- 基例如何影响使用递归函数的哪些行