c++ - How to implement two structs that can access each other? -
the code have written:
struct a; struct b; struct { 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 code not correct, don't know how implement 2 structs can access each other. there elegant way? in advance.
if want keep exact same signature of member functions, have postpone definition of member functions until both class definitions have been seen
// forward declarations struct a; struct b; struct { int v; int f(b b); // works 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 has been seen
you might use const&
function arguments (better performance when a
, b
large), have postpone function definitions until both class definitions have been seen.