3

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

Undefined structure 'User'

4

2 回答 2

3

您使用不完整类型作为类型参数,std::list根据 C++ 标准调用未定义的行为。

§17​.4.3.6/2 说,

特别是,在以下情况下效果是未定义
的: — 如果在实例化模板组件时将不完整类型(3.9)用作模板参数。

所以一种解决方案是使用不完整类型的指针。

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

这将起作用,因为指向不完整类型的指针是完整类型,即使尚未定义,编译器也可以知道Connection * 的大小等于等于。sizeof(Connection*)Connection

于 2011-06-03T11:42:46.547 回答
1

您的编译器会准确地告诉您问题所在,Connection即已声明未定义

你必须把你的Connection类型的完整定义放在你的typedef.

于 2011-06-03T11:43:35.030 回答