Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement two structs that can access each other?

The code what I have written:

    struct A;
    struct B;
    struct A
    {
        int v;
        int f(B b)
        {
            return b.v;
        }
    };

    struct B
    {
        int v;
        int f(A a)
        {
            return a.v;
        }
    };

The compile message:

|In member function 'int A::f(B)':|
11|error: 'b' has incomplete type|
7|error: forward declaration of 'struct B'|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|

I know, why that code is not correct, but I don't know how to implement two structs that can access each other. Is there any elegant way? Thanks in advance.

like image 672
Sayakiss Avatar asked Apr 25 '13 09:04

Sayakiss


1 Answers

If you want to keep the exact same signature of your member functions, you have to postpone the definition of the member functions until both class definitions have been seen

    // forward declarations
    struct A;
    struct B;

    struct A
    {
        int v;
        int f(B b); // works thanks to forward declaration
    };

    struct B
    {
        int v;
        int f(A a);
    };

    int A::f(B b) { return b.v; } // full class definition of B has been seen
    int B::f(A a) { return a.v; } // full class definition of A has been seen

You might also use const& function arguments (better performance for when A and B are large), but even then you have to postpone the function definitions until both class definitions have been seen.

like image 87
TemplateRex Avatar answered Nov 08 '22 06:11

TemplateRex