简体   繁体   中英

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])
  • 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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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