我的代码是这样的:
class RetInterface {...}
class Ret1: public RetInterface {...}
class AInterface
{
public:
virtual boost::shared_ptr<RetInterface> get_r() const = 0;
...
};
class A1: public AInterface
{
public:
boost::shared_ptr<Ret1> get_r() const {...}
...
};
此代码无法编译。
在visual studio中,它引发
C2555:重写虚函数返回类型不同且不是协变的
如果我不使用boost::shared_ptr
而是返回原始指针,代码就会编译(我知道这是由于C++中的covariant return types造成的)。我可以看到问题是因为Ret1
的boost::shared_ptr
不是从RetInterface
的boost::shared_ptr
派生的。但是我想返回Ret1
的boost::shared_ptr
以便在其他类中使用,否则我必须在返回后强制转换返回值。
发布于 2019-06-11 19:24:38
在this blog post上有一个整洁的解决方案(来自Raoul )
在添加对多重继承和抽象方法的支持之前,本文摘录如下:
template <typename Derived, typename Base>
class clone_inherit<Derived, Base> : public Base
{
public:
std::unique_ptr<Derived> clone() const
{
return std::unique_ptr<Derived>(static_cast<Derived *>(this->clone_impl()));
}
private:
virtual clone_inherit * clone_impl() const override
{
return new Derived(*this);
}
};
class concrete: public clone_inherit<concrete, cloneable>
{
};
int main()
{
std::unique_ptr<concrete> c = std::make_unique<concrete>();
std::unique_ptr<concrete> cc = b->clone();
cloneable * p = c.get();
std::unique_ptr<clonable> pp = p->clone();
}
我鼓励阅读全文。它写得很简单,解释得也很好。
https://stackoverflow.com/questions/196733
复制相似问题