C++抽象类型初始化
我有一个类接口,它有纯虚方法。在另一个类中,我有一个继承自 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
}
}
I have a class Interface, that has pure virtual methods. In another class I have a nested type that inherits from Interface and makes it non-abstract. I use Interface as a type and use the function to initialise the type, but I am getting, cannot compile because of abstract type.
Interface:
struct Interface
{
virtual void something() = 0;
}
Implementation:
class AnotherClass
{
struct DeriveInterface : public Interface
{
void something() {}
}
Interface interface() const
{
DeriveInterface i;
return i;
}
}
Usage:
struct Usage : public AnotherClass
{
void called()
{
Interface i = interface(); //causes error
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用抽象类作为指针和引用,因此您需要
加上几个分号,这样就可以正常工作。请注意,在 C++ 中只有指针和引用是多态的,因此即使
Interface
不是抽象的,由于所谓的切片,代码也会不正确。You use abstract classes as pointer and references, so you'd do
plus a couple of semicolons and it will work fine. Note that only pointers and references are polymorphic in C++, so even if
Interface
were not abstract, the code would be incorrect because of so-called slicing.您需要在此处使用接口*。
You need to work with an Interface* here.