Embedded structs and correct function calls
You're given two structs. One of type 'A', another of type 'B'. The one of type 'B' has a struct of type 'A' in it. So something like this:
struct A {
void print_stuff(A * a){ puts("From A"); }
};
struct B {
A a_part;
char * s;
void print_stuff(B * b){
printf("From B\n\t%s\n", b->s);
}
};
B * B_new(char * str) {
B * b = (B*)malloc(sizeof(struct B));
b->s = strdup(str);
return b;
}
You want to be able to call struct B's 'print_stuff' function, even with code like this:
A * aptr = (A*) B_new("foo");
aptr->print_stuff(aptr);
You are NOT allowed to use inheritance, C++ containers or classes. Struct B MUST have a_part.
How would you write your code so that regardless of the type of the pointer, the correct print_stuff function is called (in this case, if a pointer to a struct of type B was casted to A*, how would you guarant开发者_如何学Cee that the print_stuff function in B is called)?
You could make print_stuff
a function pointer, but then you need to manually hook it up to the correct function. In this case though, you're just replicating C++ inheritance mechanisms so it's pointless.
The A
object can't automatically know where it's contained, or if it's contained at all.
So the bottom line is, just use C++ inheritance.
This is really horrible. But yes, there is a way to do it. Put a bool
field in A
, and in the same place in B
, to indicate the real type. The code below should give you an appreciation of C++ (and really shouldn't be used for any other purpose).
struct A {
bool isB;
A()
{
isB=false;
}
void print_stuff(A * a);
};
struct B {
bool trueB;
A a_part;
char * s;
B()
{
isB=true;
}
void print_stuff(B * b){
printf("From B\n\t%s\n", b->s);
}
};
void A::print_stuff(A * a)
{
if(isB)
{
B* b = (B*)(this);
b->print_stuff(b);
}
else
puts("From A");
}
B * B_new(char * str) {
B * b = (B*)malloc(sizeof(struct B));
b->s = strdup(str);
b->trueB=true;
return b;
}
精彩评论