Class simulations and polymorphism, inheritance

Source: Internet
Author: User
Tags inheritance printf
In object-oriented languages, the concept of classes arises. This is an evolution of programming ideas. Class: A collection of specific operations on specific data. So the class contains two categories: Data and operations. The suct in C language is just a collection of data. (liyuming1978@163.com)

1. Example: Let's look at a small example
#ifndef c_class #define C_class suct #endif c_class A {c_class a *a_this;
       void (*foo) (C_class A *a_this);
       int A;
int b;
 
};  C_class b{//b inherited a c_class B *b_this;              Order is important void (*foo) (C_class B *bthis);
       virtual function int A;
 
       int b;
int C; 
};
 
void B_f2 (C_class B *bthis) {printf ("It is b_fun\n");} void A_foo (C_class A *athis) {printf ("It is a.a=%d\n", athis->a);//or Here//exit (1);//printf ("pure virtual does not allow execution \
 
n ");//or here} void B_foo (C_class B *bthis) {printf (" It is b.c=%d\n ", bthis->c);}
       void A_creat (Suct * p) {p->foo=a_foo;
       p->a=1; 
       p->b=2;
p->a_this=p;
       } void B_creat (Suct b* p) {p->foo=b_foo;
       p->a=11;      
       p->b=12;
       p->c=13;
p->b_this=p;
       int main (int argc, char* argv[]) {c_class A *ma,a;
 
       C_class B *mb,b; A_creat (&a);//instantiated B_creat (&B);
       mb=&b;
 
       ma=&a; Ma= (C_class A *) mb;//introduces polymorphic pointer printf ("%d\n", ma->a);/Unfortunately, the function variable has no private Ma->foo (MA);//polymorphic A.foo (&A
MP;A);//Not polymorphic B_F2 (&b)//member function, because the efficiency problem does not use the function pointer return 0;
 }

Output results:

11
It is b.c=13
It is A.a=1
It is B_fun

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.