After studying it, I was barely able to integrate it.
Writing c into OOP is quite fun.
Compiling environment: Xcode3.2.3 + gcc4.2
Copy codeThe Code is 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 codeThe Code is 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 codeThe Code is 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;
}