1、引言

面向对象编程(OOP)并不是一种特定的语言或者工具,它只是一种设计方法、设计思想。

它表现出来的三个最基本的特性就是封装、继承与多态。

很多面向对象的编程语言已经包含这三个特性了,例如 Smalltalk、C++、Java。

但是你也可以用几乎所有的编程语言来实现面向对象编程,例如 ANSI-C。要记住,面向对象是一种思想,一种方法,不要太拘泥于编程语言。

2、封装

封装就是把数据和方法打包到一个类里面。其实C语言编程者应该都已经接触过了,C 标准库 中的 fopen(), fclose(), fread(), fwrite()等函数的操作对象就是 FILE。

数据内容就是 FILE,数据的读写操作就是 fread()、fwrite(),fopen() 类比于构造函数,fclose() 就是析构函数。

这个看起来似乎很好理解,那下面我们实现一下基本的封装特性。

#ifndef SHAPE_H
#define SHAPE_H #include <stdint.h> // Shape 的属性
typedef struct {
int16_t x;
int16_t y;
} Shape; // Shape 的操作函数,接口函数
void Shape_ctor(Shape * const me, int16_t x, int16_t y);
void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy);
int16_t Shape_getX(Shape const * const me);
int16_t Shape_getY(Shape const * const me); #endif /* SHAPE_H */

这是 Shape 类的声明,非常简单,很好理解。一般会把声明放到头文件里面 “Shape.h”。

来看下 Shape 类相关的定义,当然是在 “Shape.c” 里面。

#include "shape.h"

// 构造函数
void Shape_ctor(Shape * const me, int16_t x, int16_t y)
{
me->x = x;
me->y = y;
} void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy)
{
me->x += dx;
me->y += dy;
} // 获取属性值函数
int16_t Shape_getX(Shape const * const me)
{
return me->x;
}
int16_t Shape_getY(Shape const * const me)
{
return me->y;
}

再看下 main.c

#include "shape.h"  /* Shape class interface */
#include <stdio.h> /* for printf() */ int main()
{
Shape s1, s2; /* multiple instances of Shape */ Shape_ctor(&s1, , );
Shape_ctor(&s2, -, ); printf("Shape s1(x=%d,y=%d)\n", Shape_getX(&s1), Shape_getY(&s1));
printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2)); Shape_moveBy(&s1, , -);
Shape_moveBy(&s2, , -); printf("Shape s1(x=%d,y=%d)\n", Shape_getX(&s1), Shape_getY(&s1));
printf("Shape s2(x=%d,y=%d)\n", Shape_getX(&s2), Shape_getY(&s2)); return ;
}

编译之后,看看执行结果:

Shape s1(x=,y=)
Shape s2(x=-,y=)
Shape s1(x=,y=-)
Shape s2(x=,y=)

3、继承

继承就是基于现有的一个类去定义一个新类,这样有助于重用代码,更好的组织代码。

在 C 语言里面,去实现单继承也非常简单,只要把基类放到继承类的第一个数据成员的位置就行了。

例如,我们现在要创建一个 Rectangle 类,我们只要继承 Shape 类已经存在的属性和操作,再添加不同于 Shape 的属性和操作到 Rectangle 中。

下面是 Rectangle 的声明与定义:

#ifndef RECT_H
#define RECT_H #include "shape.h" // 基类接口 // 矩形的属性
typedef struct {
Shape super; // 继承 Shape // 自己的属性
uint16_t width;
uint16_t height;
} Rectangle; // 构造函数
void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y,
uint16_t width, uint16_t height); #endif /* RECT_H */
#include "rect.h"

// 构造函数
void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y,
uint16_t width, uint16_t height)
{
/* first call superclass’ ctor */
Shape_ctor(&me->super, x, y); /* next, you initialize the attributes added by this subclass... */
me->width = width;
me->height = height;
}

我们来看一下 Rectangle 的继承关系和内存布局

因为有这样的内存布局,所以可以很安全的传一个指向 Rectangle 对象的指针到一个期望传入 Shape 对象的指针的函数中,就是一个函数的参数是 “Shape *”,你可以传入 “Rectangle *”,并且这是非常安全的。

这样的话,基类的所有属性和方法都可以被继承类继承!

#include "rect.h"
#include <stdio.h> int main()
{
Rectangle r1, r2; // 实例化对象
Rectangle_ctor(&r1, , , , );
Rectangle_ctor(&r2, -, , , ); printf("Rect r1(x=%d,y=%d,width=%d,height=%d)\n",
Shape_getX(&r1.super), Shape_getY(&r1.super),
r1.width, r1.height);
printf("Rect r2(x=%d,y=%d,width=%d,height=%d)\n",
Shape_getX(&r2.super), Shape_getY(&r2.super),
r2.width, r2.height); // 注意,这里有两种方式,一是强转类型,二是直接使用成员地址
Shape_moveBy((Shape *)&r1, -, );
Shape_moveBy(&r2.super, , -); printf("Rect r1(x=%d,y=%d,width=%d,height=%d)\n",
Shape_getX(&r1.super), Shape_getY(&r1.super),
r1.width, r1.height);
printf("Rect r2(x=%d,y=%d,width=%d,height=%d)\n",
Shape_getX(&r2.super), Shape_getY(&r2.super),
r2.width, r2.height); return ;
}

输出结果:

Rect r1(x=,y=,width=,height=)
Rect r2(x=-,y=,width=,height=)
Rect r1(x=-,y=,width=,height=)
Rect r2(x=,y=,width=,height=)

4、多态 C++

语言实现多态就是使用虚函数。在 C 语言里面,也可以实现多态。 现在,我们又要增加一个圆形,并且在 Shape 要扩展功能,我们要增加 area() 和 draw() 函数。但是 Shape 相当于抽象类,不知道怎么去计算自己的面积,更不知道怎么去画出来自己。而且,矩形和圆形的面积计算方式和几何图像也是不一样的。

下面让我们重新声明一下 Shape 类

#ifndef SHAPE_H
#define SHAPE_H #include <stdint.h> struct ShapeVtbl;
// Shape 的属性
typedef struct {
struct ShapeVtbl const *vptr;
int16_t x;
int16_t y;
} Shape; // Shape 的虚表
struct ShapeVtbl {
uint32_t (*area)(Shape const * const me);
void (*draw)(Shape const * const me);
}; // Shape 的操作函数,接口函数
void Shape_ctor(Shape * const me, int16_t x, int16_t y);
void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy);
int16_t Shape_getX(Shape const * const me);
int16_t Shape_getY(Shape const * const me); static inline uint32_t Shape_area(Shape const * const me) //用于虚函数调用
{
return (*me->vptr->area)(me);
} static inline void Shape_draw(Shape const * const me)//用于虚函数调用
{
(*me->vptr->draw)(me);
} Shape const *largestShape(Shape const *shapes[], uint32_t nShapes);
void drawAllShapes(Shape const *shapes[], uint32_t nShapes); #endif /* SHAPE_H */

看下加上虚函数之后的类关系图

4.1 虚表和虚指针

虚表(Virtual Table)是这个类所有虚函数的函数指针的集合。

虚指针(Virtual Pointer)是一个指向虚表的指针。这个虚指针必须存在于每个对象实例中,会被所有子类继承。

在《Inside The C++ Object Model》的第一章内容中,有这些介绍。

4.2 在构造函数中设置vptr

在每一个对象实例中,vptr 必须被初始化指向其 vtbl。

最好的初始化位置就是在类的构造函数中。

事实上,在构造函数中,C++ 编译器隐式的创建了一个初始化的vptr。

在 C 语言里面, 我们必须显示的初始化vptr。

下面就展示一下,在 Shape 的构造函数里面,如何去初始化这个 vptr。

#include "shape.h"
#include <assert.h> // Shape 的虚函数
static uint32_t Shape_area_(Shape const * const me);
static void Shape_draw_(Shape const * const me); // 构造函数
void Shape_ctor(Shape * const me, int16_t x, int16_t y)
{
// Shape 类的虚表
static struct ShapeVtbl const vtbl =
{
&Shape_area_,
&Shape_draw_
};
me->vptr = &vtbl;
me->x = x;
me->y = y;
} void Shape_moveBy(Shape * const me, int16_t dx, int16_t dy)
{
me->x += dx;
me->y += dy;
} int16_t Shape_getX(Shape const * const me)
{
return me->x;
}
int16_t Shape_getY(Shape const * const me)
{
return me->y;
} // Shape 类的虚函数实现
static uint32_t Shape_area_(Shape const * const me)
{
assert(); // 类似纯虚函数
return 0U; // 避免警告
} static void Shape_draw_(Shape const * const me)
{
assert(); // 纯虚函数不能被调用
} Shape const *largestShape(Shape const *shapes[], uint32_t nShapes)
{
Shape const *s = (Shape *);
uint32_t max = 0U;
uint32_t i;
for (i = 0U; i < nShapes; ++i)
{
uint32_t area = Shape_area(shapes[i]);// 虚函数调用
if (area > max)
{
max = area;
s = shapes[i];
}
}
return s;
} void drawAllShapes(Shape const *shapes[], uint32_t nShapes)
{
uint32_t i;
for (i = 0U; i < nShapes; ++i)
{
Shape_draw(shapes[i]); // 虚函数调用
}
}

4.3 继承 vtbl 和 重载 vptr

上面已经提到过,基类包含 vptr,子类会自动继承。但是,vptr 需要被子类的虚表重新赋值。并且,这也必须发生在子类的构造函数中。下面是 Rectangle 的构造函数。

#include "rect.h"
#include <stdio.h> // Rectangle 虚函数
static uint32_t Rectangle_area_(Shape const * const me);
static void Rectangle_draw_(Shape const * const me); // 构造函数
void Rectangle_ctor(Rectangle * const me, int16_t x, int16_t y,
uint16_t width, uint16_t height)
{
static struct ShapeVtbl const vtbl =
{
&Rectangle_area_,
&Rectangle_draw_
};
Shape_ctor(&me->super, x, y); // 调用基类的构造函数
me->super.vptr = &vtbl; // 重载 vptr
me->width = width;
me->height = height;
} // Rectangle's 虚函数实现
static uint32_t Rectangle_area_(Shape const * const me)
{
Rectangle const * const me_ = (Rectangle const *)me; //显示的转换
return (uint32_t)me_->width * (uint32_t)me_->height;
} static void Rectangle_draw_(Shape const * const me)
{
Rectangle const * const me_ = (Rectangle const *)me; //显示的转换
printf("Rectangle_draw_(x=%d,y=%d,width=%d,height=%d)\n",
Shape_getX(me), Shape_getY(me), me_->width, me_->height);
}

4.4 虚函数调用

有了前面虚表(Virtual Tables)和虚指针(Virtual Pointers)的基础实现,虚拟调用(后期绑定)就可以用下面代码实现了。

uint32_t Shape_area(Shape const * const me)
{
return (*me->vptr->area)(me);
}

这个函数可以放到.c文件里面,但是会带来一个缺点就是每个虚拟调用都有额外的调用开销。为了避免这个缺点,如果编译器支持内联函数(C99)。

我们可以把定义放到头文件里面,类似下面:

static inline uint32_t Shape_area(Shape const * const me)
{
return (*me->vptr->area)(me);
}

如果是老一点的编译器(C89),我们可以用宏函数来实现,类似下面这样:

#define Shape_area(me_) ((*(me_)->vptr->area)((me_)))

看一下例子中的调用机制:

4.5 main.c

#include "rect.h"
#include "circle.h"
#include <stdio.h> int main()
{
Rectangle r1, r2;
Circle c1, c2;
Shape const *shapes[] =
{
&c1.super,
&r2.super,
&c2.super,
&r1.super
};
Shape const *s; // 实例化矩形对象
Rectangle_ctor(&r1, , , , );
Rectangle_ctor(&r2, -, , , ); // 实例化圆形对象
Circle_ctor(&c1, , -, );
Circle_ctor(&c2, , -, ); s = largestShape(shapes, sizeof(shapes)/sizeof(shapes[]));
printf("largetsShape s(x=%d,y=%d)\n", Shape_getX(s), Shape_getY(s)); drawAllShapes(shapes, sizeof(shapes)/sizeof(shapes[])); return ;
}

输出结果:

largetsShape s(x=,y=-)
Circle_draw_(x=,y=-,rad=)
Rectangle_draw_(x=-,y=,width=,height=)
Circle_draw_(x=,y=-,rad=)
Rectangle_draw_(x=,y=,width=,height=)

5、总结

还是那句话,面向对象编程是一种方法,并不局限于某一种编程语言。

用 C 语言实现封装、单继承,理解和实现起来比较简单,多态反而会稍微复杂一点,如果打算广泛的使用多态,还是推荐转到 C++ 语言上,毕竟这层复杂性被这个语言给封装了,你只需要简单的使用就行了。

但并不代表,C 语言实现不了多态这个特性。

转自:

https://blog.csdn.net/onlyshi/article/details/81672279

C语言实现面向对象(转)的更多相关文章

  1. [java学习笔记]java语言核心----面向对象之this关键字

    一.this关键字 体现:当成员变量和函数的局部变量重名时,可以使用this关键字来区别:在构造函数中调用其它构造函数 原理:         代表的是当前对象.         this就是所在函数 ...

  2. 第二十五节:Java语言基础-面向对象基础

    面向对象 面向过程的代表主要是C语言,面向对象是相对面向过程而言,Java是面向对象的编程语言,面向过程是通过函数体现,面向过程主要是功能行为. 而对于面向对象而言,将功能封装到对象,所以面向对象是基 ...

  3. 如何使用C语言的面向对象

    我们都知道,C++才是面向对象的语言,但是C语言是否能使用面向对象的功能? (1)继承性 typedef struct _parent { int data_parent; }Parent; type ...

  4. 比较分析C++、Java、Python、R语言的面向对象特征,这些特征如何实现的?有什么相同点?

    一门课的课后题答案,在这里备份一下: 面向对象程序设计语言 –  比较分析C++.Java.Python.R语言的面向对象特征,这些特征如何实现的?有什么相同点? C++ 语言的面向对象特征: 对象模 ...

  5. 用C语言实现面向对象的开发

    C语言的对象化模型 面向对象的特征主要包括: .封装,隐藏内部实现 .继承,复用现有代码 .多态,改写对象行为 采用C语言实现的关键是如何运用C语言本身的特性来实现上述面向对象的特征. 1.1 封装 ...

  6. 基于C语言的面向对象编程

    嵌入式软件开发中,虽然很多的开发工具已经支持C++的开发,但是因为有时考虑运行效率和编程习惯,还是有很多人喜欢用C来开发嵌入式软件.Miro Samek说:"我在开发现场发现,很多嵌入式软件 ...

  7. 已看1.熟练的使用Java语言进行面向对象程序设计,有良好的编程习惯,熟悉常用的Java API,包括集合框架、多线程(并发编程)、I/O(NIO)、Socket、JDBC、XML、反射等。[泛型]\

    1.熟练的使用Java语言进行面向对象程序设计,有良好的编程习惯,熟悉常用的Java API,包括集合框架.多线程(并发编程).I/O(NIO).Socket.JDBC.XML.反射等.[泛型]\1* ...

  8. luajit利用ffi结合C语言实现面向对象的封装库

    luajit中.利用ffi能够嵌入C.眼下luajit的最新版是2.0.4,在这之前的版本号我还不清楚这个扩展库详细怎么样,只是在2.04中,真的非常爽.  既然是嵌入C代码.那么要说让lua支持 ...

  9. go语言之面向对象

    Go 语言结构体 Go 语言中数组可以存储同一类型的数据,但在结构体中我们可以为不同项定义不同的数据类型. 结构体是由一系列具有相同类型或不同类型的数据构成的数据集合. 结构体表示一项记录,比如保存图 ...

  10. C 语言实现面向对象编程

    转载 https://blog.csdn.net/onlyshi/article/details/81672279 C 语言实现面向对象编程1.引言面向对象编程(OOP)并不是一种特定的语言或者工具, ...

随机推荐

  1. 用chrony代替ntpd时间同步服务器

    Chrony是一个开源的自由软件,它能保持系统时钟与时钟服务器(NTP)同步,让时间保持精确. 它由两个程序组成:chronyd和chronyc. chronyd是一个后台运行的守护进程,用于调整内核 ...

  2. 00073_Math类

    1.Math类概述 (1)Math 类是包含用于执行基本数学运算的方法的数学工具类,如初等指数.对数.平方根和三角函数: (2)类似这样的工具类 ,其所有方法均为静态方法,并且一般不会创建对象.如Sy ...

  3. 畅通project续HDU杭电1874【dijkstra算法 || SPFA】

    http://acm.hdu.edu.cn/showproblem.php?pid=1874 Problem Description 某省自从实行了非常多年的畅通project计划后.最终修建了非常多 ...

  4. nyist oj 115 城市平乱 (最短路径)

    城市平乱 时间限制:1000 ms  |  内存限制:65535 KB 难度:4 描写叙述 南将军统领着N个部队.这N个部队分别驻扎在N个不同的城市. 他在用这N个部队维护着M个城市的治安.这M个城市 ...

  5. SharePoint 2013 开启訪问请求

    1.通常,我们进入SharePoint 2013网站,假设没权限会提示该网站未被共享,而没有切换账号或者申请訪问,实在是非常流氓:事实上,SharePoint为我们提供了訪问请求页面.可是可能须要手动 ...

  6. Android 推断程序在手机中是否是活动状态或者正在执行状态

    沈阳斌子在今天项目需求上碰到个这种问题,在Service中须要推断当前的程序是否是活动状态,换句话说也就是说后台跑的服务中有业务需求检測当前程序是否是该服务的程序 这样好让点击推送通知时跳转到不同的页 ...

  7. 【翻译自mos文章】 11gR1版本号 asmcmd的新命令--cp、md_backup、md_restore

    11gR1版本号 asmcmd的新命令--cp.md_backup.md_restore 參考原文: ASMCMD - New commands in 11gR1 (Doc ID 451900.1) ...

  8. audio_coding模块分析和audio_conference_mixer模块分析

    audio_coding 1. 主要接口      AudioCodingModuleImpl::RegisterReceiveCodec 初始化Codec      AudioCodingModul ...

  9. 51NOD 1686 第K大区间 二分

    第k大区间   定义一个区间的值为其众数出现的次数.现给出n个数,求将所有区间的值排序后,第K大的值为多少. Input   第一行两个数n和k(1<=n<=100000,k<=n* ...

  10. ROS中安装任意版本的OPENCV

    转自:http://tieba.baidu.com/p/5023000237 安装 Opencv 3.2 on Ubuntu 16.04 并创建node测试 step 1: 安装一些package s ...