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
开发者_Python百科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.
P.S. This was due already and I solved it with reinterpret_cast
. I was wondering if there was a more elegant way.
What you can do is to create two unions. As long as you don't interchange them you will be fine.
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;
};
精彩评论