If i have a class name app and a class name manager. I want to create inside manager class an app class, I've seen two options but I didn't understand the difference.
choice 1:
//.....
class app; //writing this line outside the declaration of the func
class manager{
//..
private:
app *a;
//...
}
or choice 2开发者_Python百科:
class manager{
//..
private:
app *a;
//..
}
I think you're talking about forward declaration. If so, then read this:
C++ INCLUDE Rule : Use forward declaration when possible
Read also this FAQ:
[39.12] What special considerations are needed when forward declarations are used with member objects?
The class app;
outside your class manager { ... }
is a forward declaration. It tells the compiler, "app
is a class. I'm not going to tell you what it looks like, but trust me, it is."
Think of your compiler as only knowing about this particular file (which I am assuming is a .h
file) when it compiles. You have said that your member
class includes a pointer to an "app
". "What the heck is an app?" the compiler wants to know. Without the forward declaration (or perhaps an #include app.h
or something similar), it doesn't know, and will fail to compile. By saying at the top, class app;
, it knows that app
is a class. That's all it needs to know to allocate the space for a pointer to it in your member
class.
Look, your "choice 2" isn't valid C++. Who knows what was on your mind... Maybe you wanted to write something like this:
class manager {
//..
private:
class app *a;
//..
}
In this case we define pointer to app
class, which is unknown here. This can be used instead of #include "app.h"
, because all pointers are of the same size and you can define a pointer without defining that app
class. Your first example does the same thing, but allows you to omit class
word in all subsequent definitions of pointers to it.
The first example includes a forward declaration of the class app
so that you can declare pointers to it in later code. The second example doesn't mention app
at all before you attempt to use it, so the compiler will not accept it. The compiler needs to know what the name app
refers to before you can use it to declare additional things.
Since you're only declaring a pointer, you don't yet need to have a full declaration of app
. But in order for your program to fully compile and link, you'll need to define app
eventually. Possibly within the same file, or possibly in some other file. But somewhere before you attempt to create an instance of that class or use any of its member variables and functions.
精彩评论