在 c++11 标准中,如果 B 类继承自 A 类,则“B 是一个 A”。 但是,我仍然对这个概念感到困惑: 看看这段代码:
class Base {
public:
virtual ~Base() {}
virtual Base* clone() const = 0;
};
class Derived : public Base {
public:
virtual Base* clone() const {
return new Derived(*this);
}
//<more functions>
};
我们从 Derived 返回了一个指向 Base 的指针,但是如果在这段代码中使用这种方法:
Derived* d1 = new Derived();
Derived* d2 = d1->clone();
我们所做的是在 Derived*
中分配 Base*
!!
问题:
为什么这段代码不能编译?如何修改(为什么?)以适应继承?
最佳答案
即使经过一些微不足道的编辑(我所做的),您发布的代码也不会编译。 Derived::clone()
的签名应该是:
virtual Derived* clone() const override { // <-- return type
return new Derived(*this);
}
即使 clone()
的返回类型在Base
和 Derived
类不同,它是对 virtual
的有效覆盖功能,因为 co-variance在 C++ 中是合法的。
当您按照问题中所述处理指针时,不会有任何切片。
Derived::clone()
应该返回 Derived*
.
是否clone()
应该是 virtual
或不取决于设计,但与virtual
析构函数这是个好主意。
另一种方法是使用 template
并避免 virtual
:
class Base {
public:
virtual ~Base() {}
template<class T> // now need not add this trivial code in all derived classes
T* clone() const { return new T(*this); }
};
关于抽象类中的c++克隆函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28273777/