您的位置:首页 > 编程语言 > C语言/C++

C语言用结构体模拟类的功能

2015-07-20 20:59 225 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/kakabest123/article/details/46973705

之前一直觉得C语言里面的结构体和C++里面的类有千丝万缕的联系,和同事们谈论时候总因为这个被喷,回来仔细研究了一下。

/********* first.h *********/
#ifndef __FIRST__H_H
#define __FIRST__H_H
//打开TYPE__A 或 TYPE__B的作用是相同的
//#define TYPE__A
#define TYPE__B
char *my_get_char(char *str);
int my_get_int(int in);
#ifdef TYPE__A
struct test_st
{
int elem;
char* (*get_char)(char *str);
int (*get_int)(int in);
};
#endif
#ifdef TYPE__B
typedef char* (*type_get_char)(char *str);
typedef int (*type_get_int)(int in);
struct test_st
{
int elem;
type_get_char get_char;
type_get_int get_int;
};
#endif
typedef struct test_st a_test_st;
#endif
/********* first.h *********/
/********* first.c *********/
#include <stdio.h>
#include <string.h>
#include "first.h"
int main( void )
{
a_test_st *aTestSt;
char aStr[] = "abcdefg";
char *pStr = NULL;
int aInt = 0;
aTestSt = (a_test_st*)malloc(sizeof( a_test_st));//申请内存空间
memset(aTestSt, 0, sizeof(a_test_st));//对aTestSt中所有元素地址初始化为0
aTestSt->elem = 45;//为结构中变量赋值
aTestSt->get_char = my_get_char;//为aTestSt中函数指针赋值
aTestSt->get_int = my_get_int;//为aTestSt中函数指针赋值
pStr = aTestSt->get_char( aStr);//调用aTestSt的函数
printf("aStr = %s/n",aStr);
aInt = aTestSt->get_int( aTestSt->elem);//调用aTestSt的函数
printf("aInt = %d/n", aInt);
free(aTestSt);//释放aTestSt所指向内存空间
aTestSt = NULL;//置空
return 0;
}
char *my_get_char(char *str)
{//将str前两个字符返回
char *pstr = NULL;
pstr = str;
*pstr = *str;
*(pstr + 1) = *(str + 1);
*(pstr + 2) = '/0';

return pstr;
}
int my_get_int(int in)
{
return in + 2;
}
/********* first.c *********/
打开TYPE__A 或 TYPE__B的作用是相同的


是可以通过结构体以及函数指针实现在结构体中加入函数的。


结构体和类做比较的时候,一个很大的区别就是结构体相当于数据的集合,而类在保存数据的同时也有对相应数据的函数处理,现在用函数指针的话,就没有这个区别了。

因此,觉得学习不应该学的太死,只会死记表象和概念上的区别,还应该深入学习思想、本质方面的内容。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: