如何转发声明 C++类从另一个类继承?
我知道我可以按如下方式转发声明一个类:
class Foo;
// ... now I can use Foo*
但是,我可以这样做:
class Bar {
public:
virtual void someFunc();
};
// ... somehow forward declare Class Foo as : public Bar here
someFunc(Foo* foo) {
foo -> someFunc();
}
class Foo: public Bar {
}
?
谢谢!
I know that I can forward declare a class as follows:
class Foo;
// ... now I can use Foo*
However, can I do something like this:
class Bar {
public:
virtual void someFunc();
};
// ... somehow forward declare Class Foo as : public Bar here
someFunc(Foo* foo) {
foo -> someFunc();
}
class Foo: public Bar {
}
?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将 Bar 转发声明为
class Bar;
并更改someFunc
的签名以采用Bar*
作为参数。由于someFunc()
是基类中的虚拟方法,因此它应该可以工作。You can forward declare Bar as
class Bar;
and change the signature ofsomeFunc
to take aBar*
as parameter. SincesomeFunc()
is a virtual method in the base class, it should work.在您的前向声明之后,
Foo
成为不完整类型,并且在您提供Foo
的定义之前,它将保持不完整状态。虽然
Foo
不完整,但任何取消引用Foo
指针的尝试都是错误的。因此,要编写您需要提供
Foo
的定义。After your forward declaration
Foo
becomes an incomplete type and it will remain incomplete until you provide the definition ofFoo
.While the
Foo
is incomplete any attempt to dereference a pointer toFoo
is ill-formed. So to writeyou need to provide
Foo
's definition.