相关疑难解决方法(0)

如何使用带有智能指针的协变返回类型?

我有这样的代码:

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 {...}
     ...
};
Run Code Online (Sandbox Code Playgroud)

此代码无法编译.

在视觉工作室,它提出

C2555:覆盖虚函数返回类型不同且不协变

如果我不使用boost::shared_ptr但返回原始指针,代码编译(我理解这是由于C++中的协变返回类型).我可以看到这个问题是因为boost::shared_ptrRet1不是源自boost::shared_ptrRetInterface.但我想返回boost::shared_ptrRet1在其他类使用,否则我必须在返回后投返回值.

  1. 难道我做错了什么?
  2. 如果没有,为什么这样的语言 - 它应该是可扩展的,以处理这种情况下智能指针之间的转换?有一个理想的解决方法吗?

c++ smart-pointers covariance

63
推荐指数
2
解决办法
1万
查看次数

标签 统计

c++ ×1

covariance ×1

smart-pointers ×1