不能在其他文件中包含结构
Can't include struct in another file
我正在用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.h
struct account
,login.h
需要从lista.h
lista
。因此,我们还添加了前向声明。有关详细信息,请参阅此链接。您的最终代码将是:
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.h
lista.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;
};
相关文章:
- 结构包含在两个头文件中,这两个文件我都不拥有
- 包含矢量指针的结构的内存释放问题
- 包含 std::list 的结构体的 C++ 初始化
- 不能在其他文件中包含结构
- 使用包含结构的数组的成员函数
- 删除包含结构的向量的向量
- 如何声明包含结构的类的成员函数
- C++包含结构的结构 SIGSEGV
- 复制包含结构的向量
- 我们如何在 c++ 实现文件中包含结构
- 类,其中包含结构.C++
- 反转指向成员的指针(即获取包含结构的地址)
- 编译包含结构的h文件时发生链接错误
- 如何擦除包含结构的地图 包含结构的地图
- 包含结构的向量的向量
- 使用Vector包含结构的指针问题
- 对包含结构的deque进行排序
- java c++传递一个包含c++结构的向量的向量
- 向量包含结构的排序
- 返回包含结构