我有这样的代码:
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_ptr的Ret1不是源自boost::shared_ptr的RetInterface.但我想返回boost::shared_ptr的Ret1在其他类使用,否则我必须在返回后投返回值.
我感兴趣的是是否可以使用 复制虚拟构造函数模式的行为(例如,参见虚拟构造函数示例)std::shared_ptr。由于明显的原因(无效的协变返回类型),用共享指针替换原始指针的方法失败了。如果有人知道支持智能指针的任何替代方案,我很感兴趣。
项目中到处都使用智能指针,类似虚拟构造函数的方法似乎是解决我当前正在解决的问题的唯一方法。
代码如下:
class A
{
public:
virtual std::shared_ptr<A> clone(void) const = 0;
virtual void mymethod() const = 0;
};
class B : public A
{
std::shared_ptr<B> clone(void) const
{
return (new B(*this));
}
void mymethod() const
{
std::cout << "type something";
}
};
class C
{
public:
void mymethod(std::shared_ptr<A const> MyB)
{
std::shared_ptr<A const> MyB2 = MyB -> clone();
MyB2 -> mymethod();
}
};
Run Code Online (Sandbox Code Playgroud)