使用接口作为共享指针参数

And*_*ers 0 c++ interface

如何将派生自接口的类传递给以接口为参数的函数?

我有一个接口和一个类设置类似这样的东西。

class Interface
{
public:
    virtual ~Interface() {}
    virtual void DoStuff() = 0;
};

class MyClass : public Interface
{
public:
    MyClass();
    ~MyClass();
    void DoStuff() override;
};

void TakeAnInterface(std::shared_ptr<Interface> interface);

int main()
{
    auto myInterface = std::make_shared<MyClass>();
    TakeAnInterface(myInterface);
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨No matching function call to TakeAnInterface(std::shared_ptr<MyClass>&)。为什么功能TakeAnInterface不能接收Interface类而不是MyClass?

Som*_*ude 5

因为myInterfacestd::shared_ptr<MyClass>和不是的实例std::shared_ptr<Interface>,并且类不能自动相互转换。

您不能使用std::make_shared,必须明确:

auto myInterface = std::shared_ptr<Interface>(new MyClass);
Run Code Online (Sandbox Code Playgroud)

  • 像这样创建的shared_ptr `auto myInterface = std::shared_ptr&lt;Interface&gt;(new MyClass);` 与`auto myInterface = std::make_shared&lt;MyClass&gt;();` 不同。首先将创建指向指针的指针(2 次跳转),因此速度较慢。检查我的解决方案:`auto myInterface = static_cast&lt;std::shared_ptr&lt;Interface&gt;&gt;(std::make_shared&lt;MyClass&gt;());`。 (2认同)
  • @Payne如果我见过的话,那是一个令人费解且很可能过早的优化。另外,我的解决方案中的“问题”不是关于指针的指针(双重间接),而是有两种内存分配,而不仅仅是一种。 (2认同)