【问题标题】:Use an interface as shared pointer parameter [duplicate]使用接口作为共享指针参数[重复]
【发布时间】:2016-01-07 09:55:57
【问题描述】:

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

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

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

编译器抱怨No matching function call to TakeAnInterface(std::shared_ptr&lt;MyClass&gt;&amp;)。为什么函数 TakeAnInterface 不接收 Interface 类而不是 MyClass?

【问题讨论】:

  • MyClassInterface 的转换是自动的,而从std::shared_ptr&lt;MyClass&gt;std::shared_ptr&lt;Interface&gt; 没有明显的转换
  • 这段代码应该可以正常编译。你用的是哪个编译器?
  • 你发布了你的真实代码吗?只有当您参考时才会出现错误消息。请发布真实代码,而不是您在输入问题时编造的代码...

标签: c++ interface


【解决方案1】:

因为myInterfacestd::shared_ptr&lt;MyClass&gt; 而不是std::shared_ptr&lt;Interface&gt; 的实例,并且类之间不会自动相互转换。

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

auto myInterface = std::shared_ptr<Interface>(new MyClass);

【讨论】:

  • 为什么它被否决了?
  • 是的,就是这样!谢谢你:)
  • 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;());.
  • @Payne 如果我见过这样的优化,那是一种令人困惑且很可能是过早的优化。此外,我的解决方案的“问题”不是指针指针(双重间接),而是有两个内存分配而不是一个。
猜你喜欢
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 2017-01-09
  • 2012-09-09
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
相关资源
最近更新 更多