Studied it, and finally managed to digest it.
c It's fun to write oop.
Compilation Environment: xcode3.2.3+gcc4.2
Copy Code code as follows:
#ifndef Object_h
#define Object_h
typedef void (*execute) (struct Object *a_this);
typedef struct OBJECT* (*allocate) ();
typedef struct _OBJECT_VTABLE
{
Char *name;
Execute EXE;
}object_vtable;
typedef struct _BASECMD
{
Object_vtable Vtable;
}basecmd;
---for common---//
basecmd* New (Allocate NEWOBJ);
void Delete (void * item);
// --------------------------//
---for basecmd---//
basecmd* Newbasecmd ();
void Exe_basecmd (Basecmd *a_this);
// --------------------------//
---for homecmd---//
typedef struct _HOMECMD
{
Object_vtable Vtable;
}homecmd;
basecmd* Newhomecmd ();
void Exe_homecmd (Homecmd *a_this);
// --------------------------//
#endif
Copy Code code as follows:
#include "Cloud.h"
---for common---//
basecmd* New (Allocate NEWOBJ)
{
Basecmd * obj = NEWOBJ ();
return obj;
}
void Delete (void * Item)
{
Free (item);
}
// --------------------------//
---for basecmd---//
basecmd* Newbasecmd ()
{
Basecmd * cmd = malloc (sizeof (basecmd));
Cmd->vtable.name = "Cloud";
Cmd->vtable.exe = Exe_basecmd;
return cmd;
}
void Exe_basecmd (Basecmd *a_this)
{
printf ("do base command =%s/n", a_this->vtable.name);
}
// --------------------------//
---for homecmd---//
basecmd* Newhomecmd ()
{
Homecmd * cmd = malloc (sizeof (homecmd));
Cmd->vtable.name = "Home";
Cmd->vtable.exe = Exe_homecmd;
return cmd;
}
void Exe_homecmd (Homecmd *a_this)
{
printf ("Do home command =%s/n", a_this->vtable.name);
}
// --------------------------//
Copy Code code as follows:
#include <stdio.h>
#include <stdlib.h>
#include "Cloud.h"
int main (int argc, const char * argv[])
{
basecmd* cmd = new (Newbasecmd);
Cmd->vtable.exe (CMD);
Delete (cmd);
basecmd* cmd2 = new (Newhomecmd);
Cmd2->vtable.exe (CMD2);
Delete (CMD2);
return 0;
}