2关于克隆方法的问题

2 Questions about clone method

本文关键字:问题 方法 于克隆      更新时间:2024-09-22

我有两个问题。

  1. 是否需要在派生类中添加virtual关键字?

  2. Derived::clone()方法中返回Derived类的指针和返回Base类的指针有什么区别吗?

class Base
{
virtual Base* clone() const = 0;
};

class Derived : public Base
{
virtual Derived* clone() const;
};
  1. 没有必要,但强烈建议[1]在开头添加virtual,或在结尾添加-preferred-override[2]。

  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(或更高版本(。