如何在结构能见度其他文件方面的表现? [英] How do structs behave in terms of visibility to other files?

查看:65
本文介绍了如何在结构能见度其他文件方面的表现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从一个答案采取不同的问题上SO:

This is taken from an answer to a different question on SO:

一个结构定义是私有的源文件,除非放置在一个
  共享的头文件。没有其他的源文件都可以访问的成员
  结构,即使给定的指针结构(因为布局并不
  在其他编译单元知道)。

A structure definition is private to a source file unless placed in a shared header file. No other source file can access the members of the struct, even if given a pointer to the struct (since the layout is not known in the other compilation unit).

如果该结构需要在别处使用,它必须仅作为
  指针。把表格结构structname的正向声明;
  typedef结构structname structname;在headerfile,和使用
  structname *其他地方在codeBase的。然后,由于
  结构成员只出现在一个源文件,结构的
  内容是有效的私人到该文件。

If the struct needs to be used elsewhere, it must be used only as a pointer. Put a forward declaration of the form struct structname; typedef struct structname structname; in the headerfile, and use structname * everywhere else in your codebase. Then, since the structure members appear only in one source file, the structure's contents are effectively 'private' to that file.

这混淆了我。为什么你只能用指针来一个结构即使包含声明(但没有定义的话)一个头文件?

This confuses me. Why can you only use pointers to a struct even if you include a header file that declares it (but does not define it)?

我的意思是,如果我包括头部声明的函数,它是在一个单独的实现文件中定义的函数,我仍然可以访问该function--为什么结构有什么不同?为什么他们的成员是私有的,即使你能得到的声明?

I mean, if I include a header that declares a function, a function which is defined in a separate implementation file, I can still access that function-- why are structs different? Why are their members private even if you can get to the declaration?

推荐答案

它无关的可见性。报价是指一个结构的向前声明的(所以,没有定义可用)

It has nothing to do with visibilty. The quote is referring to a struct forward declaration (so, no definition available)

头有效包含类似:

struct X;  // No definition available

一个向前声明引入了的不完全型的。很少有东西,你可以用一个不完整的类型做,但他们中的一个指针声明(不取消引用它)。

A forward declaration introduces an incomplete type. There are very few things you can do with an incomplete type, but one of them is declaring a pointer (not dereferencing it).

只要编译器不知道该结构的大小或它的成员(它肯定不能用一个简单的向前声明),也不会允许的X任何声明,也没有指向任何访问一个 X

As long as the compiler doesn't know the size of the struct, or it's members (it certainly can't with a simple forward declaration), it won't allow any declaration of an X, nor any dereferencing of a pointer to an X.

这篇关于如何在结构能见度其他文件方面的表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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