Using C language to practice OOP and new,delete in-depth analysis of _c language

Source: Internet
Author: User
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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.