Class Link for Parents

I am new to using C ++, and in fact I settled on a problem.

I have class A, B, C defined as follows (PSEUDOCODE)

class A
{
...
    DoSomething(B par1);
    DoSomething(C par1);
...
}

class B
{
   A parent;
...
}

class C
{
   A parent;
...
}

The problem is this:

How to do it? If I just do it (as I always did in C #), it gives errors. I pretty much understand the reason for this. (A is not yet announced if I add the link (including) B and C to my own header)

How to get around this problem? (Using the void * pointer is not an imho path)

+3
source share
4 answers

Forward-declare B C. , , A.

class B;
class C;

// At this point, B and C are incomplete types:
// they exist, but their layout is not known.
// You can declare them as function parameters, return type
// and declare them as pointer and reference variables, but not normal variables.
class A
{
    ....
}

// Followed by the *definition* of B and C.

. S.

, , (, #): const, :

class A
{
...
    void DoSomething(const B& par1);
    void DoSomething(const C& par1);
...
}
+5

, , :

class B;
class C;

class A
{
...
    R DoSomething(B par1);
    R DoSomething(C par1);
...
}

class B
{
   A parent;
...
}

class C
{
   A parent;
...
}

inline R A::DoSomething(B par1) { ... }
inline R A::DoSomething(C par1) { ... }

, B C. , inline, .

+3

B C A:

class B;
class C;

class A {
    ...
};

At the point where B and C are referenced within A, the compiler only needs to know what kind of animals they are. By using a direct declaration you satisfy the compiler. Then you can define them correctly.

+2
source

use forward declaration

You can define class A; without its implementation, before B and C, and then define it later

+1
source

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


All Articles