简体   繁体   English

多个文件中的c ++联合

[英]c++ union in multiple files

I'm sorry this is long, but it is a little complicated to explain. 很抱歉,这很长,但是解释起来有点复杂。

We recently had to hand in for homework the following program (much simplified here): 我们最近不得不交以下程序(这里已大大简化)进行家庭作业:

  • Some type of structure (class/struct) representing a physical block of data (just a char[1024]) 表示物理数据块的某种类型的结构(类/结构)(仅是char [1024])
  • Two types of logical partitioning of this block 该块的两种逻辑分区

For example: 例如:

struct p {
  char[1024]
}
struct l1 {
  int num;
  char name[20];
}
struct l2 {
  int num;
  char type[10];
  char filler[400];
  bool flag;
}

The obvious thing to me was to have a union 对我来说,显而易见的是有一个工会

union {
  p phy;
  l1 logi1;
  l2 logi2;
}

but the problem was that part of the specification (the part I cut out to simplify it) was that the physical stuff be in a separate file then the logical stuff. 但是问题在于规范的一部分(我为简化该部分而剪切掉了)是物理物料位于一个单独的文件中,而逻辑物料位于一个单独的文件中。

So now the question is: Is there a way to add fields to the union (I assume not) or another way to have functions in the 'physical' file accept 'logical' blocks and use them as raw blocks? 所以现在的问题是:是否有一种方法可以将字段添加到联合中(我认为不是),或者可以通过其他方法在“物理”文件中具有功能,可以接受“逻辑”块并将其用作原始块?

I hope this is clear. 我希望这很清楚。

PS This was due already and I solved it with reinterpret_cast . PS这已经到期了,我用reinterpret_cast解决了。 I was wondering if there was a more elegant way. 我想知道是否有更优雅的方法。

No, the entire structure of a type must be defined together. 不,必须一起定义类型的整个结构。 You cannot "re-open" a type to add things to its definition later. 您不能“重新打开”类型,以后再向其定义中添加内容。

The assignment as you stated it here asked for three types, not one type representing three things. 如您在此处所述,分配要求三种类型,而不是一种代表三件事的类型。 Your first three struct definitions were sufficient. 您的前三个结构定义就足够了。

After all three structs have been defined, you're welcome to define a union type. 在定义完所有三个结构之后,欢迎您定义一个联合类型。 Possibly something like this: 可能是这样的:

#include "physical.h"
#include "logical.h"

union combined_structure {
  p phy;
  l1 logi1;
  l2 logi2;
};

What you can do is to create two unions. 您可以做的是创建两个联合。 As long as you don't interchange them you will be fine. 只要您不互换它们,就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM