gpt4 book ai didi

c++ - 返回类型协方差与智能指针

转载 作者:IT老高 更新时间:2023-10-28 12:41:16 25 4
gpt4 key购买 nike

在 C++ 中我们可以这样做:

struct Base
{
virtual Base* Clone() const { ... }
virtual ~Base(){}
};

struct Derived : Base
{
virtual Derived* Clone() const {...} //overrides Base::Clone
};

但是,以下内容不会起到同样的作用:

struct Base
{
virtual shared_ptr<Base> Clone() const { ... }
virtual ~Base(){}
};

struct Derived : Base
{
virtual shared_ptr<Derived> Clone() const {...} //hides Base::Clone
};

在这个例子中 Derived::Clone 隐藏 Base::Clone 而不是覆盖 它,因为标准说重写成员的返回类型只能从引用(或指针)变为基数,再到引用(或指针)再到派生。有什么聪明的解决方法吗?当然有人可能会争辩说 Clone 函数无论如何都应该返回一个普通的指针,但现在让我们忘记它——这只是一个说明性的例子。我正在寻找一种方法来将虚拟函数的返回类型从智能指针更改为 Base 到智能指针 Derived

提前致谢!

更新:感谢 Iammilind

,我的第二个示例确实无法编译

最佳答案

你不能直接做,但有几种方法可以模拟它,在非虚拟接口(interface)习语的帮助下。

对原始指针使用协方差,然后包装它们

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()); }
};

这仅在您实际上有一个原始指针开始时才有效。

通过强制转换模拟协方差

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()); }
};

在这里,您必须确保 Derived::doClone 的所有覆盖确实返回指向 Derived 或派生自它的类的指针。

关于c++ - 返回类型协方差与智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6924754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com