Arm*_*yan 32 c++ virtual-functions smart-pointers return-type
在C++中我们可以这样做:
struct Base
{
virtual Base* Clone() const { ... }
virtual ~Base(){}
};
struct Derived : Base
{
virtual Derived* Clone() const {...} //overrides Base::Clone
};
Run Code Online (Sandbox Code Playgroud)
但是,以下内容不会做同样的伎俩:
struct Base
{
virtual shared_ptr<Base> Clone() const { ... }
virtual ~Base(){}
};
struct Derived : Base
{
virtual shared_ptr<Derived> Clone() const {...} //hides Base::Clone
};
Run Code Online (Sandbox Code Playgroud)
在此示例中Derived::Clone
隐藏 Base::Clone
而不是覆盖它,因为标准表示重写成员的返回类型可能仅从引用(或指针)更改为基础到引用(或指针).这有什么聪明的解决方法吗?当然有人可能认为Clone
函数应该返回一个普通的指针,但是现在让我们忘记它 - 这只是一个例证.我正在寻找一种方法来启用虚拟功能的返回类型从智能指针更改Base
为智能指针Derived
.
提前致谢!
更新:感谢 Iammilind,我的第二个例子确实无法编译
yme*_*ett 47
您无法直接执行此操作,但在非虚拟接口惯用法的帮助下,有几种方法可以模拟它.
struct Base
{
private:
virtual Base* doClone() const { ... }
public:
shared_ptr<Base> Clone() const { return shared_ptr<Base>(doClone()); }
virtual ~Base(){}
};
struct Derived : Base
{
private:
virtual Derived* doClone() const { ... }
public:
shared_ptr<Derived> Clone() const { return shared_ptr<Derived>(doClone()); }
};
Run Code Online (Sandbox Code Playgroud)
这只适用于你实际上有一个原始指针开始.
struct Base
{
private:
virtual shared_ptr<Base> doClone() const { ... }
public:
shared_ptr<Base> Clone() const { return doClone(); }
virtual ~Base(){}
};
struct Derived : Base
{
private:
virtual shared_ptr<Base> doClone() const { ... }
public:
shared_ptr<Derived> Clone() const
{ return static_pointer_cast<Derived>(doClone()); }
};
Run Code Online (Sandbox Code Playgroud)
在这里,你必须确保Derived::doClone
do的所有覆盖实际上返回指针Derived
或从它派生的类.
归档时间: |
|
查看次数: |
6459 次 |
最近记录: |