|
|
Invisible <voi### [at] devnull> wrote:
> > The only thing that's impossible for a class to have another class
> > as member variable, and that another class having the first class as
> > member variable.
> Yeah, that's exactly what I'm trying to do.
I don't think so.
> Actually, no, wait... Class X has class Y as a member, but class Y only
> /mentions/ class X. (It has member functions that return objects of
> class X.)
Sounds like a rather complicated design. Anyways, you can declare classes
(as opposed to defining them). In other words, you can do this:
//----------------------------------------
// This could be eg. in a "Y.hh" header file
class X; // declaration of X
class Y
{
public:
void foo() { std::cout << "I'm an Y\n"; }
X gimmeAnX();
};
//----------------------------------------
You can then define X for example like:
//----------------------------------------
// This could be eg. in a "X.hh" header file,
// in which case you would have a
// #include "Y.hh" here.
class X
{
Y anObjectOfY;
public:
void bar() { anObjectOfY.foo(); }
};
//----------------------------------------
After both definitions you can now implement the Y::gimmeAnX() function,
eg. like:
//----------------------------------------
// This could be eg. in a "Y.cc" source file,
// in which case you would have a
// #include "X.hh" here.
X Y::gimmeAnX() { return X(); }
//----------------------------------------
(All of the above code could be in one single source file as well,
in that order, which is why I didn't explicitly use any #include lines.)
> > (For obvious reasons. It would be an infinitely large class.)
> It can if at least one of the classes refers to the other through a
> pointer or a reference.
It wouldn't be a member variable then.
> So, the way I see it, I have two options:
> 1. Put class X and class Y in the same header file.
Not necessary (and even if you put it in the same header file, that alone
wouldn't solve your problem).
> 2. Start throwing unchecked casts around the place.
The correct solution is to use class declarations.
--
- Warp
Post a reply to this message
|
|