tags:

views:

106

answers:

3

hi, 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.

+5  A: 

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.

GMan
@gman: This does not compile, you need to put struct _PersonB in the definition of struct personA.
Phong
@Phong: A typo. Also, did you mean a pointer? That was the typo I had.
GMan
It give me: Error 1 error C2079: '_PersonA::rel' uses undefined struct '_PersonB'
complez
@gman: I made the same mistake ^^
Phong
@zeroonea: Make sure you're using the updated code, my first revision was missing a pointer. Also, take heed my advice against the typedef's.
GMan
@GMan: okay, it work now, i will stop using typedef.
complez
+1 for the typedef trick (look so obvious but since I only do C...)
Phong
+3  A: 

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
+1  A: 

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
Conistency of PTRPersonA v PtrPersonB? How am I going to remember which pointer is capitalized?
Jonathan Leffler
An unintentional typo on my part. I've fixed it.
wallyk