【发布时间】: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<MyClass>&)。为什么函数 TakeAnInterface 不接收 Interface 类而不是 MyClass?
【问题讨论】:
-
从
MyClass到Interface的转换是自动的,而从std::shared_ptr<MyClass>到std::shared_ptr<Interface>没有明显的转换 -
这段代码应该可以正常编译。你用的是哪个编译器?
-
你发布了你的真实代码吗?只有当您参考时才会出现错误消息。请发布真实代码,而不是您在输入问题时编造的代码...