[英]C++ Abstract type initialisation
我有一个类Interface,它具有纯虚方法。 在另一个类中,我有一个嵌套类型,该类型从Interface继承并使其非抽象。 我将接口用作类型,并使用函数来初始化类型,但是由于抽象类型,我无法编译。
接口:
struct Interface
{
virtual void something() = 0;
}
执行:
class AnotherClass
{
struct DeriveInterface : public Interface
{
void something() {}
}
Interface interface() const
{
DeriveInterface i;
return i;
}
}
用法:
struct Usage : public AnotherClass
{
void called()
{
Interface i = interface(); //causes error
}
}
您将抽象类用作指针和引用,因此您可以
class AnotherClass
{
struct DeriveInterface : public Interface
{
void something() {}
}
DeriveInterface m_intf;
Interface &interface() const
{
return m_intf;
}
}
struct Usage : public AnotherClass
{
void called()
{
Interface &i = interface();
}
}
再加上几个分号,它将可以正常工作。 请注意,在C ++中,只有指针和引用是多态的,因此,即使Interface
不是抽象的,由于所谓的切片,代码也不正确。
struct Base { virtual int f(); }
struct Der: public Base {
int f(); // override
};
...
Der d;
Base b=d; // this object will only have B's behaviour, b.f() would not call Der::f
您需要在此处使用Interface *。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.