I was asked to change the following C++
code to C
. I'm almost sure that C++
classes can be converted to C structs. But what happens when these classes are inherited classes , and contain some functions? Should I use pointers to functions? And what if these functions are of the Parent class?
class A {
protected:
int x;
public:
A():x(0){}
virtual void Method1()const {}
virtual void Method2(){}
void Method3()const {}
virtual ~A() {}
};
class B : public A {
public:
virtual void Method1() {}
virtual void Method4() const {}
virtual ~B(){}
};
void main(){
B* b;
b = new B;
b->Method1();
b->Method2();
b->Method3();
b->Method4();
}
Here is my partial solution (to "main" part only). I assumed that the "Methods" functions are pointers to functions within structs a and b. Is it OK?
void main(){
B* b;
A* a;
b = (B*)malloc(sizeof(B));
a = (A*)malloc(sizeof(A));
if ((b==NULL)||(a==NULL)) // memory alloc. check
return;
b->Method1=Method1_t;
b->Method2=Method2_t(a);
b->Method3=Method3_t(a);
b->Method4=Method4_t;
// MethodX_t are written as functions outside structs, main.
}
You are trying to take on too many tasks at once. I suggest adding functionality step by step.
Don't try to work on a task unless you have completed all the ones before it in the above list.
Hope that helps.
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.