开发者

C++ stl list two structures cross-reference

I have such code with 2 structures:

#include <list>

using namespace std;

struct Connection;
struct User;    

typedef list<Connection> Connections;
typedef list<User> Users;

struct User {
    Connections::iterator connection;
};

struct Connection {
    Users::iterator user;
};

But when I try to compile it, the compiler (C++ Builder XE) return me such error - "Undefined structure 'Connection'".

Can anyone help me with my problem?

@ereOn, struct Connection; struct User; struct Connection { Users::iterator user; }; typedef list Connections; typedef list Users;

struct User {
    Connections::iterator connection;
};
开发者_如何学JAVA

Undefined structure 'User'


You're using incomplete type as type argument to std::list which invokes undefined bevahior according to the C++ Standard.

§17​.4.3.6/2 says,

In particular, the effects are undefined in the following cases:
— if an incomplete type (3.9) is used as a template argument when instantiating a template component.

So one solution would be using pointer of incomplete type.

struct Connection;
struct User;    

typedef list<Connection*> Connections; //modified line
typedef list<User*> Users;             //modified line

struct User {
    Connections::iterator connection;
};

struct Connection {
    Users::iterator user;
};

This will work because pointer to an incomplete type is a complete type, the compiler can know the size of Connection* which is equal to sizeof(Connection*) even if Connection hasn't been defined yet.


Your compiler tells you exactly what the problem is, that is Connection is declared but not defined.

You have to put the complete definition of your Connection type before your typedef.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜