A variable of class A in class B and a pointer to class B in class A?

This may seem strange, but I have a problem in one of my programs where I have a class A that needs a class B variable inside it, and class B needs a pointer to class A inside it so that I can determine which class it is bound to what ....

I get errors because in class A he says class B is not defined yet, and in class B he says class A is not defined yet ...

Both of my header files, which contain separate classes, include each other, and I tried forwarding to declare my classes, for example. class A; class B; but I get compiler errors like:

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.

+3
source share
3 answers

You need to declare Abefore you define B:

class A;   // declaration of A

class B    // definition of B
{
    A* foo;
    // ...
};

class A    // definition of A
{
    B bar;
    // ...
};

This type of declaration is often referred to as a declaration.

+6
source

First of all, think about redesigning your classes. Circular dependencies are bad practice and it is likely that you could avoid this altogether with a more elegant class design.

However, you can work around the problem using direct links (at this point you need to use pointers or links) -

class B;

class A
{
   B *pPtr;
};

class B
{
   A typeA;
};
+2
source

, , , "B":

class A
{
public:
  class B* pB;
};

class B
{
public:
  A a;
};

, , , . , .

0

Source: https://habr.com/ru/post/1760206/


All Articles