当前位置: 首页 > 编程日记 > 正文

设计模式 之美 -- 面向对象(C/C++分别实现)

文章目录

      • 前言
      • 封装
        • C++实现
        • C 实现
      • 继承
        • C++ 实现
        • C实现

前言

为了保证代码的可复用性、可扩展性、可维护性,我们提出了面向对象的思想。
面向对象的核心特性有以下几个

  • 封装特性
    信息隐藏或者数据访问保护。类通过暴露有限的访问接口,授权外部仅能通过类提供的方式来访问内部信息或者数据。
    封装用来提升代码的可扩展性、可维护性
  • 继承特性
    继承是用来表示类之间的 is-a 关系,分为两种模式:单继承和多继承。单继承表示一个子类只继承一个父类,多继承表示一个子类可以继承多个父类。为了实现继承这个特性,编程语言需要提供特殊的语法机制来支持。继承主要是用来解决代码可复用性的问题
  • 多态特性
    多态是指子类可以替换父类,在实际的代码运行过程中,调用子类的方法实现。
    多态可以提高代码的可扩展性和可复用性

C++提供语法来实现以上三个特性,而C语言则可以使用函数指针来实现以上三个特性。

封装

C++实现

class Person{
private:char *pFName;char *pLName;
public:Person(const char * const str1,const char * const \str2):pFName(str1),pLNname(str2){}~Person();void Person_DisplayInfo();void Person_WriteToFile(const char* pFileName);
}void Person::Person_DisplayInfo()
{cout <<"pFName is " << this->pFName<< endl;cout <<"pLName is " << this -> pLName << endl;
}void Person::Person_WriteToFile(const char* pFileName)
{if(!pFileName) {cout <<"file name is null" << endl;return;}FILE *fp;printf("write ot file name is: %s\n",pFileName);fp = fopen(pFileName, "a+");char *buff = NULL;buff = (char *)malloc(sizeof(DATA_SIZE));if(!buff) {printf("malloc failed\n");return;}int count;strcpy(buff,this->pFName);count = fwrite(buff,sizeof(char),strlen(buff),fp);printf("write to %s's result is %d \n",pFileName,count);fclose(fp);fp = NULL;
}int main()
{Person obj("lili","chuchu");obj.Person_DisplayInfo();obj.Person_WriteToFile("test.txt");return 0;
}

C 实现

person.h

#include <stdio.h>
#include <stdlib.h>typedef struct _Person Person;//declaration of pointers to functions
typedef void    (*fptrDisplayInfo)(Person*);
typedef void    (*fptrWriteToFile)( Person*, const char*);
typedef void    (*fptrDelete)( Person *) ;typedef struct _Person {char* pFName;char* pLName;//interface for functionfptrDisplayInfo   Display;fptrWriteToFile   WriteToFile;fptrDelete      Delete;
}Person;Person* new_Person(const char* const pFirstName, const char* const pLastName); //constructorvoid delete_Person(Person* const pPersonObj);    //destructorvoid Person_DisplayInfo(Person* const pPersonObj);
void Person_WriteToFile(Person* const pPersonObj, const char* pFileName);

person.c

#include <stdio.h>
#include <stdlib.h>
#include "person.h"#define DATA_SIZE 1024 Person* new_person(const char* const pFirstName, const char* const pLastName)
{Person *obj = NULL;obj = (Person *)malloc(sizeof(Person));if(!obj){return NULL;}obj -> pFName =  malloc(sizeof(char)*(strlen(pFirstName)+1));if(!obj -> pFName) {return NULL;}strcpy(obj -> pFName, pFirstName);obj -> pLName = malloc(sizeof(char) * (strlen(pLastName) + 1));if(!obj -> pLName) {return NULL;}strcpy(obj -> pLName, pLastName);/*construct the function pointer*/obj->Delete = delete_Person;obj->Display = Person_DisplayInfo;obj->WriteToFile = Person_WriteToFile;printf("finish constructor Person\n");return obj;
}void Person_WriteToFile(Person* const pPersonObj, const char* pFileName)
{if(!pPersonObj || !pFileName) {return;}FILE *fp;printf("write ot file name is: %s\n",pFileName);fp = fopen(pFileName, "a+");char *buff = NULL;buff = (char *)malloc(sizeof(DATA_SIZE));if(!buff) {printf("malloc failed\n");return;}int count;strcpy(buff,pPersonObj->pFName);count = fwrite(buff,sizeof(char),strlen(buff),fp);printf("write to %s's result is %d \n",pFileName,count);fclose(fp);fp = NULL;
}void delete_Person(Person* const pPersonObj)
{if(!pPersonObj) {return;}if(pPersonObj -> pFName) {free(pPersonObj->pFName);pPersonObj -> pFName = NULL;}if(pPersonObj -> pLName) {free(pPersonObj -> pLName);pPersonObj -> pLName = NULL;}}void Person_DisplayInfo(Person* const pPersonObj) {if(!pPersonObj) {printf("obj is not exists, please construct\n");}printf("pFName is %s\n",pPersonObj -> pFName);printf("pLName is %s\n",pPersonObj -> pLName);
}

main.c

#include <stdio.h>
#include <stdlib.h>
#include "person.h"
//#include "employee.h"int main(int argc, char *argv[]) {Person *obj;obj = new_person("pfirst_name","plast_name");obj -> Display(obj);obj -> WriteToFile(obj,"F:\\test_write.txt");obj -> Delete(obj);return 0;
}

继承

C++ 实现

class Person{
private:char *pFName;char *pLName;
public:Person(const char * const str1,const char * const \str2):pFName(str1),pLNname(str2){}~Person(){}void Person_DisplayInfo();void Person_WriteToFile(const char* pFileName);
}class Empolyee:public Person{
private:char* pDepartment;char* pCompany;int nSalary;
public:Empolyee(const char * const str1,const char * const\str2,int num):Person(str1,str2),pDepartment(str1),pCompany(str2),nSalary(num){}~Empolyee(){}void Employee_DisplayInfo();
}
void Empolyee::Employee_DisplayInfo()
{Person_DisplayInfo();//可以访问基类的公有成员cout << "pDepartment is " << pDepartment << endl;cout << "pCompany is " << pCompany<< endl;cout << "nSalary is " << nSalary << endl;
}

C实现

person.c如上,person.h增加万能指针void *
person.h

#include <stdio.h>
#include <stdlib.h>/* run this program using the console pauser or add your own getch, system("pause") or input loop */typedef struct _Person Person;//declaration of pointers to functions
typedef void    (*fptrDisplayInfo)(Person*);
typedef void    (*fptrWriteToFile)( Person*, const char*);
typedef void    (*fptrDelete)( Person *) ;typedef struct _Person {void *pDerivedObj; char* pFName;char* pLName;//interface for functionfptrDisplayInfo   Display;fptrWriteToFile   WriteToFile;fptrDelete      Delete;
}Person;Person* new_Person(const char* const pFirstName, const char* const pLastName); //constructorvoid delete_Person(Person* const pPersonObj);    //destructorvoid Person_DisplayInfo(Person* const pPersonObj);
void Person_WriteToFile(Person* const pPersonObj, const char* pFileName);

employee.h

#include "Person.h"typedef struct _Employee Employee;typedef struct _Employee
{Person* pBaseObj;char* pDepartment;char* pCompany;int nSalary;//If there is any employee specific functions; add interface here.}Employee;Person* new_Employee(const char* const pFirstName, const char* const pLastName,const char* const pDepartment, const char* const pCompany, int nSalary);    //constructor
void delete_Employee(Person* const pPersonObj);    //destructorvoid Employee_DisplayInfo(Person* const pPersonObj);

employee.c

#include <stdio.h>
#include <stdlib.h>#include "employee.h"Person* new_Employee(const char* const pFirstName, const char* const pLastName,const char* const pDepartment, const char* const pCompany, int nSalary)
{Employee* pEmpObj;//calling base class construtorPerson* pObj = new_person(pFirstName, pLastName);//allocating memorypEmpObj = malloc(sizeof(Employee));if (pEmpObj == NULL){pObj->Delete(pObj);return NULL;}pObj->pDerivedObj = pEmpObj; //pointing to derived object//initialising derived class memberspEmpObj->pDepartment = malloc(sizeof(char)*(strlen(pDepartment)+1));if(pEmpObj->pDepartment == NULL){return NULL;}strcpy(pEmpObj->pDepartment, pDepartment);pEmpObj->pCompany = malloc(sizeof(char)*(strlen(pCompany)+1));if(pEmpObj->pCompany== NULL){return NULL;}strcpy(pEmpObj->pCompany, pCompany);pEmpObj->nSalary = nSalary;//Changing base class interface to access derived class functions//virtual destructor//person destructor pointing to destrutor of employeepObj->Delete = delete_Employee;pObj->Display = Employee_DisplayInfo;//pObj->WriteToFile = Employee_WriteToFile;printf("finish construct employee\n");return pObj;
}void delete_Employee(Person* const pPersonObj)
{if(!pPersonObj){return;}Employee* pEmpObj;pEmpObj = pPersonObj->pDerivedObj;if(pEmpObj->pDepartment) {free(pEmpObj->pDepartment);pEmpObj->pDepartment = NULL;}if(pEmpObj->pCompany) {free(pEmpObj->pCompany);pEmpObj->pCompany = NULL;}pPersonObj->Delete(pPersonObj);
}void Employee_DisplayInfo(Person* const pPersonObj) {if(!pPersonObj) {printf("pPersonObj is null\n");return;}Employee* pEmpObj;pEmpObj = pPersonObj->pDerivedObj;printf("pEmpObj's pDepartment is %s\n",pEmpObj->pDepartment);printf("pEmpObj's pCompany is %s\n",pEmpObj->pCompany);printf("pEmpObj's nSalary is %d\n",pEmpObj->nSalary);
}

main.c

#include <stdio.h>
#include <stdlib.h>
#include "person.h"
//#include "employee.h"int main(int argc, char *argv[]) {Person *obj;obj = new_person("pfirst_name","plast_name");obj -> Display(obj);obj -> WriteToFile(obj,"F:\\test_write.txt");obj -> Delete(obj);Person *pobj;pobj = new_Employee("Gauri", "Jaiswal","HR", "TCS", 40000);pobj -> Display(pobj);pobj -> Delete(pobj);return 0;
}

相关文章:

数据结构编程实战汇总

出自数据结构与算法分析第二版&#xff08;C&#xff09; 一 引论二 算法分析三 表 栈 队列四 树五 散列六 优先队列七 排序 优先队列实现事件模拟 &#xff1a;http://maozj.iteye.com/blog/676567d堆 左式堆 斜堆&#xff1a; http://blog.csdn.net/yangtrees/article/detai…

同时支持三个mysql+sqlite+pdo的php数据库类_同时支持三个MySQL+SQLite+PDO的PHP数据库类...

PHP学习教程文章简介&#xff1a; 同时支持三个MySQLSQLitePDO的PHP数据库类使用方法: // mysql connect $db new SQL(mysql:hostlocalhost;database21andy_blog;, 21andy.com_user, 21andy.com_password); // PDO SQLite3 connect $db new SQL(pdo:database/21andy.com/21an…

VB6基本数据库应用(五):数据的查找与筛选

同系列的第五篇&#xff0c;上一篇在&#xff1a;http://blog.csdn.net/jiluoxingren/article/details/9633139 数据的查找与筛选 第4篇发布到现在已经过了4天&#xff0c;很抱歉&#xff0c;学生党&#xff0c;还是悲催的高三&#xff0c;没办法&#xff0c;8月1就开学了。以后…

学习进度条(第一周)

学习进度条&#xff1a; 第一周 所花时间&#xff08;包括上课&#xff09; 5h 代码量&#xff08;行&#xff09; 150 博客量&#xff08;篇&#xff09; 2 了解到的知识点 这种主要是对上学期web知识的一个回顾&#xff0c;进行了第一次开学测验&#xff0c;了解了实…

设计模式 之美 -- 单例模式

为什么要使用单例&#xff1f; 一个类只允许创建一个对象或者实例。 背景简介&#xff1a;使用多线程并发访问同一个类&#xff0c;为了保证类的线程安全&#xff0c;可以有两种方法&#xff1a; 将该类定义为单例模式&#xff0c;即该类仅允许创建一个实例为该类的成员函数添…

(int),Int32.Parse() 和 Convert.toInt32() 的区别

在 C# 中&#xff0c;(int)&#xff0c;Int32.Parse() 和 Convert.toInt32() 三种方法有何区别? int 关键字表示一种整型&#xff0c;是32位的&#xff0c;它的 .NET Framework 类型为 System.Int32。 (int)表示使用显式强制转换&#xff0c;是一种类型转换。当我们从 int 类型…

MySQL留言板怎么创建_如何使用JSP+MySQL创建留言本(三)

如何使用JSPMySQL创建留言本(三)推荐查看本文HTML版本下面我们开始建立留言的页面&#xff01;import "java.util.*"import "java.text.*"import"java.sql.*"import "java.io.*"import "java.lang.*"contentType"t…

刚子扯谈:微信 今天你打飞机了嘛吗?

文/刚子 2013年8月5日 开片语:昨日爆爬二坨山后&#xff0c;精神豁然靓丽。虽然晒伤的不算厉害&#xff0c;但是还是有同事关切。说刚子你真黑了。好吧&#xff01;当然今天咱不扯爬山涉水&#xff0c;也不扯刚子咋就黑了&#xff0c;咱扯今天那个“热”。也许有部分朋友已经猜…

OMS API

plot cd("C:/……/") 转载于:https://www.cnblogs.com/Pusteblume/p/10467200.html

设计模式 之美 -- 简单工厂模式

文章目录1. 解决问题2. 应用场景3. 实现C实现&#xff1a;C语言实现4. 缺点1. 解决问题 举例如下&#xff1a; 我们实现一个卖衣服的功能&#xff0c;衣服的种类有很多&#xff1a;帽子&#xff0c;裤子&#xff0c;T恤。。。 每卖一种衣服&#xff0c;我们都要进行一次实例化…

mysql 分表原理_MYSQL 分表原理(转)

简介:引用MySQL官方文档中的一段话:MERGE存储引擎,也被认识为MRG_MyISAM引擎,是一个相同的可以被当作一个来用的MyISAM表的集合."相同"意味着所有表同样的列和索引信息.你不能合并列被以不同顺序列于其中的表,没有恰好同样列的表,或有不同顺序索引的表.而且,任何或者…

popStar手机游戏机机对战程序

DFS算&#xff0c;五分钟如果答案没有更新&#xff0c;那个解一般来说就很优了。 #include <cstdio> #include <iostream> #include <string.h> #include <cstdlib> #include <algorithm> #include <queue> #include <vector> #incl…

ps aux参数说明

运行 ps aux 的到如下信息&#xff1a; ps auxUSER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDsmmsp 3521 0.0 0.7 6556 1616 ? Ss 20:40 0:00 sendmail: Queue runner01:00:00 froot 3532 0.0 0.2 2428 …

myeclipse使用maven整合ssh配置

最近写项目&#xff0c;由于公司需求&#xff0c;使用myeclispe来开发maven项目&#xff0c;关于maven就不再介绍,无论是jar包管理功能&#xff0c;还是作为版本构建工具&#xff0c;优点自然是很多&#xff0c;下面先贴出所需要的配置文件。 maven所需要的 pom.xml 1 <proj…

C语言 #ifndef 引起的redefinition of xxx 问题解决

问题如下 多个.c和.h文件 其中cloth.h分布被hat.h和paths.h包含&#xff0c;编译时出现如下问题&#xff1a; error: redefinition of struct _Cloth 我的cloth.h定义如下&#xff1a; #include <stdio.h> #include <stdlib.h> #include "retval.h"…

mysql如何下载连接到visual_Visual Studio 2015 Community连接到Mysql

Visual Studio 2015 Community连接到MySQL&#xff0c;步骤很简单&#xff0c;但刚弄的时候一脸懵&#xff0c;现在记录如下以作备忘&#xff1a;安装好VS2015和Mysql后&#xff0c;只需要再安装两个东西即可。一个是SDK&#xff1a;MySQL for Visual Studio另一个是驱动&#…

web.py下获取get参数

比较简单&#xff0c;就直接上代码了&#xff1a; import web urls (/, hello ) app web.application(urls, globals()) class hello: def GET(self):print web.input()return "GET hello world"def POST(self):print web.input()return "POST hello w…

ORACLE 体系结构知识总结

ORACLE 体系结构.Oracle 体系结构图&#xff1a;.1.ORACLE 实例.1.1. Oracle 实例Oracle实例包括内存结构和后台进程System Global Area(SGA) 和Background Process 称为数据库实例文件。.2. Oracle 数据库一系列物理文件的集合&#xff08;数据文件&#xff0c;控制文件&#…

余额宝技术架构读后感

本次阅读文章为&#xff1a;余额宝技术架构及演讲 文章地址&#xff1a;https://mp.weixin.qq.com/s?__bizMzAwMDU1MTE1OQ&mid2653547540&idx1&snb3f568ba4bd1c4a0a2d35c0e5ef033cc&scene21#wechat_redirect 通过阅读“余额宝技术架构及演讲”&#xff0c;了解…

网络故障排查命令

ping #检测目标主机是否畅通traceroute #追踪路由mtr #检查到目标主机之间是否有数据包丢失nslookup #查看域名并解析&#xff0c;获取IP地址telnet #检查端口链接状态tcpdump #细致分析数据包发送接收 的详细内容netstat #查看网络端口连接状态ss #另外一种各式的查看网络端口…

Java程序猿面试题集(181- 199)

Java面试题集&#xff08;181-199&#xff09; 摘要&#xff1a;这部分是包括了Java高级玩法的一些专题&#xff0c;对面试者和新入职的Java程序猿相信都会有帮助的。 181. 182. 183. 184. 185. 186. 187. 188. 189. 190. 191. 192. 193. 194. 195. 196. 197. 198. 199. 转载于…

mysql四维数组_MySQL如何实现数组功能

前段时间想要用数组功能实现某些需求&#xff0c;结果发现mysql不支持数组&#xff0c;这个确实让人很头痛。查阅官方文档&#xff0c;也没有这一方面的资料。结果在网上&#xff0c;看到了某仁兄贴出了变相实现的一种方法&#xff0c;代码如下&#xff1a;DELIMITER ;DROP DAT…

在iOS上使用ffmpeg播放视频

国外靠谱的有这几个&#xff1a;1、Mooncatventures group https://github.com/mooncatventures-group2、KxMoviePlayer (use OpenGLES, Core Audio) https://github.com/kolyvan/kxmovie3、FFmpeg for ios (with OpenGLES, AudioQueue) https://github.com/flyhawk007/FFmpeg-…

shell --- trap 抓取信号

1. 解决问题 针对部分运行在生产环境中的脚本来说&#xff0c;有一些脚本运行的过程是不能被中断的&#xff0c;比如&#xff1a;生产环境 定期备份脚本&#xff0c;为了保证备份安全&#xff0c;备份期间不能被 SIGTERM和SIGINT 之类的中断信号中断。 该种类型的脚本逻辑增加…

python运行错误怎么查找_求助,python的二分法查找,按照视频上的代码写下来,结果运行错误...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼def bsearch(s,e,first,last,calls):print(first,last,calls)if (last-first) < 2: return s[first] e or s[last]mid first (last - first)/2if s[mid] e: return Trueif s[mid] > e: return bsearch(s,e,first,mid-1,c…

system.out 汉字乱码

使用sts时&#xff0c;文件编码都设置成了UTF-8&#xff0c;使用system.out.println输出汉字时&#xff0c;出现乱码。 解决方案&#xff1a; run>run configurations>common>encoding修改为gbk就可以了。转载于:https://www.cnblogs.com/javaleon/p/4075341.html

三阶段day1

1、动态网页 和 静态网页动态网页&#xff1a;数据可以进行交互 动态改变数据2、nodenode是基于chrome的V8引擎的Javscript运行环境node中的事件机制以及非阻塞式的I/O式模型 使其轻量又高效node中的npm 是全球最大的包管理器 &#xff08;全球最大的垃圾网站&#xff09;I:inp…

Oracle 12c DG备库Alert报错ORA-01110

环境是12.2.0.1 version, Oracle Data Guard备库近段时间一直报错&#xff0c;但是备库主库同步一致&#xff0c;数据一致。2019-03-06T23:42:22.18404808:00 Errors in file /u01/app/oracle/diag/rdbms/ccdb/ccdb/trace/ccdb_m000_129832.trc: ORA-01110: data file 7: /u01/…

linux的 计划任务机制,自己带节奏

文章目录1. 解决问题2. 计划任务分类3. 一次性计划任务实现添加计划步骤注意事项4. 周期性计划任务实现cron和crontab命令5. 延时计划任务6. flock脚本加锁&#xff0c;保证单实例运行1. 解决问题 环境中有脚本需求&#xff0c;周期性运行或者固定时间运行脚本&#xff0c;为了…

erlang的tcp服务器模板

改来改去&#xff0c;最后放github了&#xff0c;贴的也累&#xff0c;蛋疼 还有一个tcp批量客户端的&#xff0c;也一起了 大概思路是 混合模式 使用erlang:send_after添加recv的超时处理 send在socket的option里面可以设置超时 accept&#xff0c;connect都可以在调用的时候传…