OOC-use C to implement object-oriented

Source: Internet
Author: User
1. Summary C language is a process-oriented programming language, while C ++ is an object-oriented language derived from C. In fact, many C ++ implementations are implemented in C language at the underlying layer. For example, in Visual C ++, interfaces are actually struct. You can find the definition of interfaces. You can find such macro definitions: # ifndef interface # define interface struct # endifc ++ adds many new mechanisms (inheritance, polymorphism, etc.) at the language level. In C language, we can also use this mechanism, the premise is that we have to implement it on our own. This article describes how to implement encapsulation, inheritance, and Polymorphism in C language. 2. Before introducing C language encapsulation, inheritance, and polymorphism, we will introduce several concepts and syntaxes in C language. (1) struct in C language, an object is often encapsulated with a struct to facilitate operations on the object, such as: 1 strcut point {int X; int y ;}; struct can be nested. Therefore, you can regard a struct as a member of another struct, for example, 1 struct circle {struct point _; int radius ;}; this struct is exactly the same as the following definition (including the memory layout): 1 struct circle {int X; int y; int radius ;}; (2) A function pointer is a type of pointer that points to the first address of a function (the name of a function is the first address of a function). You can use a function pointer to call a function. For example, function: int func (int A [], int N); you can declare the function pointer: int (* pfunc) (int A [], int N) as follows: pfunc = func; (* pfunc) (a, n); [or pfunc (A, n)] You can use typedef to define a function pointer type, for example, typdef int (* func) (int A [], int N) can be used as follows: int cal_a (func fptr, int A [], int N) {// implementation body} (3) extern, staticextern, and static are two modifiers in C language. extern can be used to modify functions or variables, indicating that the variables or functions are defined in other files; static can also be used to modify a function or variable, indicating that the function or variable can only be used in this file. They can be used to hide or restrict access to data or functions. 3. encapsulated in the C language, you can use the structure + function pointer to simulate the implementation of the class, and the variable defined with this structure is the object. The main meaning of encapsulation is to hide internal behaviors and information. The user only needs to see external interfaces and public information. There are two methods to implement encapsulation: (1) using the C language syntax. Declare in the header file and define it in the C file. In this way, internal information can be hidden. Because external users do not know the size of the memory occupied by the object, they cannot create such objects statically. They can only be created by calling the creation function provided by the class. The disadvantage of this method is that it does not support inheritance because the child class does not have any information about the parent class. For example: // header file: Point. h # ifndef point_h # define point_h struct point; typedef struct point; point * new_point (); // newer a Point Object void free_point (point * point _); // free the allocated space # endif // C file: Point. C # include "point. h "strcut point {int X; int y ;}; point * new_point () {point * new_point _ = (point *) malloc (sizeof (point )); return new_point _;} void free_point (point * point _) {If (Poin T _ = NULL) return; free (point _);} (2) put private data information in an opaque priv variable or struct. Only the implementation code of the class knows the real definition of priv or struct. For example: # ifndef point _ H # define point_h typedef struct point; typedef struct pointprivate; strcut point {struct pointprivate * PP;}; int get_x (point * point _); int get_y (point * point _); point * new_point (); // newer a Point Object void free_point (point * point _); // free the allocated space # endif // C file: Point. C # include "point. h "struct pointprivate {int X; int y;} int get_x (point * Poin T _) {return point _-> PP-> X;} int get_y (point * point _) {return point _-> PP-> Y ;} // others ..... 4. Inheritance in the C language, you can use the fact that "the layout of the structure in the memory is consistent with the declaration of the structure" to implement inheritance. For example, we need to design a plotting tool. The objects involved may be point and circle. Since the circle is composed of points, all of them can be seen as circle inherited from point. In addition, both point and circle require space application, space release, and other operations. All of them have a common base class. // Memory management class new. h # ifndef new_h # define new_h void * New (const void * class ,...); void Delete (void * item); void draw (const void * Self); # endif // C file of the memory management class: New. C # include "New. H "# include" base. h "void * New (const void * _ base ,...) {const struct base * base = _ base; void * P = calloc (1, base-> size); Assert (p); * (const struct base **) P = base; If (base-> ctor) {va_list AP; va_start (AP, _ base ); P = base-> ctor (p, & AP); va_end (AP);} return P;} void Delete (void * Self) {const struct base ** CP = self; if (Self & * CP & (* CP)-> dtor) Self = (* CP)-> dtor (Self); free (Self );} void draw (const void * Self) {const struct base * const * CP = self; Assert (Self & * CP & (* CP)-> draw ); (* CP)-> draw (Self);} // base class: base. h # ifndef base_h # define base_h struct base {size_t size; // class space Vo Id * (* ctor) (void * Self, va_list * APP); // constructor void * (* dtor) (void * Self ); // destructor void (* draw) (const void * Self); // drawing}; # endif // point header file (external interface): Point. h # ifndef point_h # define point_h extern const void * point;/* usage: New (point, x, y); */# endif // point internal header file (not visible outside): Point. R # ifndef point_r # define point_r struct point {const void * base; // inheritance, base class pointer, placed in the first position, const prevents modification of int X, Y; // coordinates }; # Endif // Point file C: Point. C # include "Point. H "# include" New. H "# include" point. H "# include" point. R "static void * point_ctor (void * _ Self, va_list * APP) {struct point * Self = _ self; self-> X = va_arg (* app, INT ); self-> Y = va_arg (* app, INT); return self;} static void point_draw (const void * _ Self) {const struct point * Self = _ self; printf ("draw (% d, % d)", self-> X, self-> Y);} sta TIC const struct base _ point = {sizeof (struct point), point_ctor, 0, point_draw}; const void * point = & _ point; // test program: Main. C # include "Point. H "# include" New. h "int main (INT argc, char ** argv) {void * P = new (point, 1, 2); Draw (p); Delete (p) ;}similarly, to inherit the point, the circle can be as follows: 1 struct circle {const struct point; // first, the table can inherit the int radius ;}; 5. polymorphism can be achieved by using the universal pointer void * in C language. The following example is provided: 1 // test main. c void * P = new (point, 1, 2); void * PP = new (circle, 1, 2); Draw (P ); // The draw function implements the multi-state draw (PP), delete (P), delete (PP); 6. The C language can simulate the characteristics of object-oriented language, including polymorphism, inheritance, encapsulation, etc. Now many open-source software have implemented these features using C language, including PostgreSQL, a large-scale open-source database system, and a portable C language Object-Oriented Framework gobject, wireless Binary Runtime Environment brew. The C language is used to realize polymorphism, inheritance, and encapsulation, so that the software can have better readability and scalability. 7, reference (1) the C language extern and static usage: http://www.cnblogs.com/hishope/archive/2008/08/28/1278822.html (2) the three, the use of gobject-Private Members and static variables: http://blog.csdn.net/wormsun/archive/2009/11/25/4874465.aspx (3) The skills: program polymorphism in C language: http://www.ibm.com/developerworks/cn/linux/l-cn-cpolym/index.html? CA = Drs-(4) Books object-oriented programming with ANSI-C 8. Code download http://code.google.com/p/cppdatastructurelib/source/browse/#svn%2Ftrunk%2Fooc%253Fstate%253Dclosed

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.