问题描述
我知道我可以做:
class Foo;
但我可以转发声明一个类继承自另一个类,如:
but can I forward declare a class as inheriting from another, like:
class Bar {};
class Foo: public Bar;
示例用例是共变式引用返回类型。
An example use case would be co-variant reference return types.
// somewhere.h
class RA {}
class RB : public RA {}
...然后在另一个标题中不包含somewhere.h
... and then in another header that doesn't include somewhere.h
// other.h
class RA;
class A {
public:
virtual RA* Foo(); // this only needs the forward deceleration
}
class RB : public RA; // invalid but...
class B {
public:
virtual RB* Foo(); //
}
编译器处理 RB * B:Foo()
的声明是 RB
具有 RA
作为公共基类。现在很清楚,如果你打算对任何类型的反引用从 Foo
的返回值,你需要somehere.h。但是,如果一些客户端从不调用 Foo
,那么没有理由让它们包含可能显着加快编译速度的aherehere.h。
The only information the compiler should need to process the declaration of RB* B:Foo()
is that RB
has RA
as a public base class. Now clearly you would need somewhere.h if you intend to do any sort of dereferencing of the return values from Foo
. However, if some clients never calls Foo
, then there is no reason for them to include somewhere.h which might significantly speed compilation.
推荐答案
向前声明只对告诉编译器有一个名字的类存在,并且会在其他地方声明和定义。你不能在编译器需要关于类的上下文信息的任何情况下使用它,也不能使用它来告诉它只有一点关于类。 (通常,只有在没有其他上下文的情况下引用该类时,才能使用向前声明,例如作为参数或返回值。)
A forward declaration is only really useful for telling the compiler that a class with that name does exist and will be declared and defined elsewhere. You can't use it in any case where the compiler needs contextual information about the class, nor is it of any use to the compiler to tell it only a little bit about the class. (Generally, you can only use the forward declaration when referring to that class without other context, e.g. as a parameter or return value.)
在任何场景中声明Bar,然后使用它来帮助声明Foo,它的展开没有意义,有一个包含基类的向前声明 - 什么告诉你除了什么?
Thus, you can't forward declare Bar in any scenario where you then use it to help declare Foo, and it flat-out doesn't make sense to have a forward declaration that includes the base class -- what does that tell you besides nothing?
这篇关于在C ++中,是否可以转发声明一个类继承自另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!