结构的前向声明 [英] Forward declaration of struct

查看:59
本文介绍了结构的前向声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个头文件a.h,并在其中声明了一个结构.该结构的名称是 file .在 file 里面,我有3个成员:a,b,c.在a.cpp中,我实现了该结构,并为该结构变量分配了一些值.

I have a header file a.h and inside that I have declared one structure. The name of that structure is file. Inside file I have 3 members: a, b, c. In a.cpp I have implemented that structure and assigned some values to that structure variable.

现在我还有另一个文件b.h.在其中,我具有结构 file 的前向声明.到目前为止,如果我进行编译,它不会显示错误,但是当我打算通过b.cpp类访问该结构中存在的变量时,它将给出类似未定义的结构"的错误.

Now I have another file b.h. Inside it I have a forward declaration of the structure file. Until this point if I compile it's not showing an error but when I am going to access the variable present in that structure through that b.cpp class it will give an error like "undefined struct".

我在做什么错了?

推荐答案

错误的根本原因是什么?

当您正向声明一个类型时,编译器会将其视为不完整类型.

When you Forward declare a type, the compiler treats it as an Incomplete type.

前向声明告诉编译器该类型存在,并且仅与该特定类型无关.因此,您不能对此执行任何操作(例如创建对象或取消引用该类型的指针).需要编译器知道其内存布局的类型.

The forward declaration tells the compiler that the said type exists and nothing more about the particular type.So, You cannot perform any action(like creating objects, or dereferencing pointers to that type) on that type which needs compiler to know its memory layout.

解决方案:

如果需要引用结构成员,则无法转发声明,需要在源文件中包含头文件.这将确保编译器知道该类型的内存布局.您将必须相应地设计项目.

You cannot forward declare if you need to deference the structure members, You will need to include the header file in the source file.This would ensure that the compiler knows the memory layout of the type. You will have to design your project accordingly.

这篇关于结构的前向声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆