简体   繁体   中英

How to convert C++ inherited classes with functions to C style?

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.

Deal with only one class

  1. Support the equivalent of a simple class, a class with only member variables but no member functions.
  2. Support the equivalent of a class with non-virtual member functions.
  3. Support the equivalent of a class with non-virtual member functions as well as virtual member functions.

Deal with a base class and a derived class

  1. Support the equivalent of a simple derived class with only member variables and without any member functions, neither in the base class nor in the derived class.
  2. Support the equivalent of a derived class with non-virtual member functions only the base class.
  3. Support the equivalent of a derived class with non-virtual member functions in the base class as well as the derived class.
  4. Support the equivalenet of a derived class with virtual member functions only in the base class as well as non-virtual member functions.
  5. Support the equivalent of a derived class with virtual member functions as well as non-virtual member functions in the base class and the derived class.

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.

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