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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With