开发者

typedef struct problem

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.


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.


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;
};


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;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜