Two classes and built-in functions

I have two classes, and both of them use some other classes, for example:

// class1.h
class Class1;
#include "class2.h"

class Class1 {
  public:
  static Class2 *C2;
  ...
};

// class2.h
class Class2;
#include "class1.h"

class Class2 {
  public:
  static Class1 *C1;
  ...
};

And when I define it, as in the example above, it works (I also have #ifndefit to avoid endless repeatability of the header). But I also want to add some built-in functions to my classes. And I read here that I have to put the definition of the inline function in the header file, because it will not work if I put them in a cpp file and want to call them from another cpp file (when I do this, I get an undefined link during the link ) But the problem here is this:

// class1.h
...
inline void Class1::Foo() {
  C2->Bar();
}

I get the error: Invalid use of incomplete type 'struct Class2.

So how can I do this?

+4
3

, , . , , , , .

A.hpp

#ifndef INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD
#define INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD

struct B;

struct A {
  B* p;
  void foo();
};

#include "B.hpp"

inline
void A::foo() {
  if (p) p->bar();
}

#endif

B.hpp

#ifndef INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8
#define INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8

struct A;

struct B {
  A* p;
  void bar();
};

#include "A.hpp"

inline
void B::bar() {
  if (p) p->foo();
}

#endif
+8

. :

// class1.h
class Class2;

class Class1 {
  public:
  static Class2 *C2;
  ...
};

// class2.h
class Class1;

class Class2 {
  public:
  static Class1 *C1;
  ...
};

. :

class Class1; // or Class2

, . . : ", !" , , .

+2

My suggestion is that you put common methods and members into a base class, and then derive C1 and C2 from the base class. This can fix the circular dependency problem.

0
source

All Articles