2

I'm new in c++, how to made code below work (compile without a syntax error)?

typedef struct _PersonA{
    char name[128];
    LPPersonB rel;
}PersonA, *LPPersonA;

typedef struct _PersonB{
    char name[128];
    LPPersonA rel;
}PersonB, *LPPersonB;

Please, don't ask me why I need to do it like this, because it is just an example to explain my question.

Earlz
  • 62,085
  • 98
  • 303
  • 499
complez
  • 7,882
  • 11
  • 48
  • 56

3 Answers3

5

You have to forward declare:

struct _PersonB;

typedef struct _PersonA{
char name[128];
_PersonB* rel; // no typedef
}PersonA, *LPPersonA;

typedef struct _PersonB{
char name[128];
LPPersonA rel;
}PersonB, *LPPersonB;

That said, this is very...ugly. Firstly, there is no need for the typedef in C++:

struct PersonB;

struct PersonA
{
    char name[128];
    PersonB* rel;
};

struct PersonB
{
    char name[128];
    PersonA* rel;
};

Which also has the side-effect of getting rid of your bad name: _PersonA. This name is reserved for the compiler because it begins with an underscore followed by a capital letter.

And that's it. Hiding pointers behind typedef's is generally considered bad, by the way.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
3

LPPersonB is not define when you are declaring thestruct PersonA. You have to work with pointer for this:

// declare this so the compiler know that struct _PersonaB exist (even if it does not know its implementation)
typedef struct _PersonaA PersonaA;
typedef struct _PersonaB PersonaB;

// define PersonaA
struct _PersonA{
  char name[128];
  PersonB *rel; // does not need to know personB implemenation since it is a pointer
} ;

// define PersonA
struct _PersonB{
  char name[128];
  PersonA *rel;
};
Phong
  • 6,600
  • 4
  • 32
  • 61
1

There are several ways. One is:

typedef struct _PersonA PersonA, *PtrPersonA;
typedef struct _PersonB PersonB, *PtrPersonB;

struct _PersonA {
    char        name[128];
    PtrPersonB  rel;
};

struct _PersonB {
    char         name[128];
    PtrPersonA   rel;
};

Another is:

struct _PersonA {
    char             name[128];
    struct _PersonB  *rel;
};

struct _PersonB {
    char             name[128];
    struct _PersonA  *rel;
};
wallyk
  • 56,922
  • 16
  • 83
  • 148