不能在其他文件中包含结构

Can't include struct in another file

本文关键字:包含 结构 文件 其他 不能      更新时间:2023-10-16

我正在用c ++制作一个多文件项目。 我有这个代码:

利斯塔·

struct elem
{
account info;
elem* next;
};
typedef elem* lista;

此处显示的错误是声明了"lista* a"。

登录.h:

struct account
{
string user = "";
int hash_pass = 0;
};
struct list
{
lista* a;
int size;
};

login.cc:

#include "login.h"
#include "lista.h"
....

lista.cc

#include "login.h"
#include "lista.h"
....

在 lista.cc 和 login.cc 中,我包含了login.h和lista.h,但在login.h中不识别lista是类型的名称。

循环依赖!假设string类型在头文件的其他位置明确定义(可能是std::string?(,这是因为您以错误的顺序包含文件。

#include "login.h"
#include "lista.h" 
....

这基本上相当于:

struct account
{
string user = "";
int hash_pass = 0;
};
struct list
{
lista* a;
int size;
};
struct elem
{
account info;
elem* next;
};
typedef elem* lista;
....

如您所见,lista甚至在typedef之前出现,这就是您收到错误的原因。

显然,您不想关心包含头文件的顺序,因此正确的解决方案是使用适当的标头保护将lista.h包含在login.h中。但在这种情况下,这还不够:这里有循环依赖关系,因为lista.h需要从login.hstruct accountlogin.h需要从lista.hlista。因此,我们还添加了前向声明。有关详细信息,请参阅此链接。您的最终代码将是:

lista.h

#ifndef LISTA_H_
#define LISTA_H_
struct account; // forward declaration
struct elem
{
account* info; // notice that `account` now has to be a pointer
elem* next;
};
typedef elem* lista;
#endif

login.h

#ifndef LOGIN_H_
#define LOGIN_H_
#include "lista.h"
struct account
{
string user = "";
int hash_pass = 0;
};
struct list
{
lista* a;
int size;
};
#endif

如果你想在 B.h 中使用在 A.h 上声明的东西,你需要在 B.h 中包含 A.hlogin.hlista.h

在login.h中包含lista.h,因为您的登录标头需要访问lista :)

您的问题归结为:

struct elem
{
account info;   // <<< account is not known here
elem* next;     // elem is not known here
};
typedef elem* lista;   
struct account
{
std::string user = "";
int hash_pass = 0;
};
struct list
{
lista* a;
int size;
};    
typedef elem* lista;

如果您更正声明的顺序,它可以很好地编译:

struct account
{
std::string user = "";
int hash_pass = 0;
};
struct elem
{
account info;
elem* next;
};
typedef elem* lista;
struct list
{
lista* a;
int size;
};