• C语言面向对象编程


    什么是面向对象

    为了说明C语言也可以面向对象编程,有必要说一下面向对象中的几个概念:

    • 一切事物皆对象
    • 对象具有封装和继承特性
    • 对象与对象之间使用消息通信,各自存在信息隐藏

     

    可以看出,面向对象只是一种思想,与具体语言无关,只要实现了这几条就是所谓的面向对象了。

    看具体代码:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct _CClass
    {
        //添加属性
        struct _CClass *self;    //类本身,相当于C++中的this
        int a;
        int b;
        //添加方法
        void (*print)(void *self);
    
    } CParent;
    
    
    #define EXTERND_CLASS_FROM_CParent \
            void (*print)(void *self);    \
            int a;                    \
            int b;                    \
            
    
    
    typedef struct _CChild
    {
        //继承CParent
        EXTERND_CLASS_FROM_CParent
        //添加属性
        CParent parent;
        int c;
        int d;
        //添加方法
    
        void (*sayHello)();
    
    } CChild;
    
    void print(void *self);
    void sayHello();
    int main(int argc, char const *argv[])
    {
        CParent *parent=(CParent *)malloc(sizeof(CParent));
    
        //为属性赋值
        parent->a=1;
        parent->b=2;
        parent->print=print;
        //调用方法
        parent->print((void *)parent);
    
        free((void *)parent);
    
        //继承
        CChild *child=(CChild *)malloc(sizeof(CChild));
        child->a=3;
        child->b=5;
        child->print=print;
        child->sayHello=sayHello;
        child->print((void *)child);
        child->sayHello();
        free((void *)child);
        //多态
        
        CChild *child1=(CChild *)malloc(sizeof(CChild));
        CParent *parent1=(CParent *)child1;
    
        parent1->a=5;
        parent1->b=6;
        parent1->print=print;
        parent1->print((void *)child1);
    
        free((void *)child1);
    
        return 0;
    }
    
    
    void print(void *self)
    {
        CParent *tmp=(CParent *)self;
        printf("a=%d,b=%d\n",tmp->a,tmp->b);
    }
    
    
    void sayHello()
    {
        printf("Hello World! \n");
    }
  • 相关阅读:
    S2-020 Struts ClassLoader Manipulation安全限制绕过(CVE-2014-0094)
    几本关于PHP安全的书
    招聘软件开发实习生
    招聘安全测试工程师
    Fortify对移动应用安全的支持
    安全测试服务方案
    对比AppScan Source和Fortify扫描AltoroJ的结果
    JAVA白盒安全测试需要关注的API
    Java安全防御学习笔记V1.0
    appscan 安全漏洞修复办法
  • 原文地址:https://www.cnblogs.com/qinshizhi/p/3043492.html
Copyright © 2020-2023  润新知