Why other class names are specified above a class? [duplicate]
Possible Duplicate:
When to use forward declaration?
What is the use of specifying other class names above a particular class?
class A;
class B;
class C
{
...
...
};
It's a forward declaration.
As a hangover from C, the C++ compiler works in a top-to-bottom fashion (more or less). If you want your class C
to refer to class A
or class B
in some way (via a pointer or a reference), then the compiler must know about their existence beforehand.
That is called a forward declaration. It allows you to declare a pointer to the type without including its definition. Of course, since the definition doesn't exist at this pointas far as the compiler is concerned, you can only declare pointers or references to the type as the compiler would not know how to construct an object of said type, i.e., it cannot not determine its size.
By forward declaring classes like that, you are telling the compiler that the classes exist, and not to worry, you will link them in later.
This is instead of including the header files with the full definition, and is sufficient if the compiler doesn't need to know what the class looks like. For example if you are only using pointers or references to the class in the current file.
This is called forward declaration and allows the use of those classes in the defined class's prototype.
精彩评论