2关于克隆方法的问题
2 Questions about clone method
我有两个问题。
-
是否需要在派生类中添加
virtual
关键字? -
在
Derived::clone()
方法中返回Derived
类的指针和返回Base
类的指针有什么区别吗?
class Base
{
virtual Base* clone() const = 0;
};
class Derived : public Base
{
virtual Derived* clone() const;
};
-
没有必要,但强烈建议[1]在开头添加
virtual
,或在结尾添加-preferred-override
[2]。 -
不同的是,当您已经意识到您有一个正在克隆的
Derived
类时,您不需要强制转换:
Derived d;
Derived* pd = d.clone(); // without covariant return types,
// you'd need to cast here
[1] 一个值得注意的例外是,当您希望在模板基类中参数化给定方法是否为virtual
时。
[2] 即使c++98没有override
,我仍然建议使用这个:
#if __cplusplus >= 201103L
#define OVERRIDE override
#else
#define OVERRIDE
#endif
这样,您就可以无缝地从c++98转到c++11(或更高版本(。
相关文章:
- 最小硬币更换问题(自上而下方法)
- 使用同一类中的方法重新分配字段时出现问题
- 我想直接在结构中插入,但没有一种方法可以正确避免填充问题
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 此动态编程问题的自上而下方法
- 此解决方案中生成更改的方法数量(自上而下)有什么问题?
- 使用模板方法为标头提供空 cpp 时出现问题
- 这种针对 N Queen 问题的回溯方法不正确吗?
- C++ push() 和 pop() 方法使用指针的动态 LinkedList 的问题
- CreateFileA方法出现问题
- 必须使用尾随返回类型的示例,因为无法用旧方法解决问题
- 双重检查创建单例问题的方法
- C++ 指针问题 - 通过方法更新指针
- C++隐式/显式模板方法专用化问题
- 迭代快速排序方法的分区算法问题
- 单独的类声明和方法定义文件问题
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- 如何通过动态规划方法解决这个问题?
- C++ 03 类模板 这是转换构造函数还是转换运算符?以及如何声明解决此问题的方法
- 一个c++语法问题:方法的类