Variable of class A in class B and pointer of class B in class A?
This may seem weird but I have a problem 开发者_JS百科in one of my programs where I have a class A which needs a variable of class B inside it, and the class B needs a pointer to class A inside it, so that I can determine which class is attached to what....
I get errors because in class A it says that the class B is not defined yet, and in class B it says class A isn't defined yet...
Both of my header files which contain the separate classes include each other and I have tried to forward declare my classes e.g. class A; class B; but I get compiler errors such as:
error C2079: 'CFrame::menu' uses undefined class 'CMenu'
I need a pointer to class A in class B because I want to pass it to another class later on.
You need to declare A
before you define B
:
class A; // declaration of A
class B // definition of B
{
A* foo;
// ...
};
class A // definition of A
{
B bar;
// ...
};
This kind of declaration is often referred to as a forward declaration.
First of all, consider redesigning your classes. Circular dependencies are bad practice, and chances are that you could avoid this altogether with a more elegant class design.
That said, you can get around the problem using forward references (at which point, you need to use pointers or references) -
class B;
class A
{
B *pPtr;
};
class B
{
A typeA;
};
You may be able to avoid forward declaration by simply specifying what a "B" is:
class A
{
public:
class B* pB;
};
class B
{
public:
A a;
};
If you're having problems with this, it may be because you're including implementation along with your declarations. If you separate the implementation and the header, you might have fewer problems in this scenario.
精彩评论