c的struct,c++的class与go中的struct区别

来源:互联网 发布:淘宝在哪买二手手机 编辑:程序博客网 时间:2024/05/29 17:36

1、接口的实现:
c通过struct也是可以实现接口的,通过c中struct实现c++的class。

class a {public:    int add(int a, int b)    {        return a + b;    }private:    int int_a;    int b;};int main() {    a class_a;    int sum = class_a.add(1, 2);}

a 类class_a是无法调用private:b只能调用int add();
只要将变量int a,int int_b进行封装,让结构体无法直接调用就可以了。

#include "stdio.h"#include "struct_1.h"typedef  struct A_{    int a;}struct_a;//typedef  struct C_ {//  int c1;//  int c2;//} struct_c;typedef struct B_ {    struct_a a;    struct_c c;     int b;}struct_b;int main() {    struct_b b_struct;    //b_struct.c = new_c();    b_struct.a.a = 1;    b_struct.b = 3;    b_struct.c.c1 = 2;}

这样要调用c1必须要经过c不可以直接调用。需要初始化结构体struct_a a;struct_c c; 吗?
不需要。因为编译连接的时候会直接分配空间,在struct_b里面的结构体a,c是可以提前为其分配空间的。
这里写图片描述这里写图片描述
但是这样封装存在一个问题,class中的函数是如何调用这个结构体呢?
所以应该封装是结构体的指针。如果是结构体的指针,会按指针长度分配4个字节的空间的。依然是cc,cc,cc…,所以还需要对分配完的指针进行初始化。c中是不存在构造函数的,所以这个也需要实现。

struct_c * new_c() {    struct_c *p;    p = (struct_c *)malloc(sizeof(struct_c));    return p;}    b_struct.c = new_c();

这样c1,c2相当于class中的private。
下面要在struct中添加函数了,struct不可以直接写入函数,但是可以运用函数指针。

2、函数指针。

#include "stdio.h"struct  a {    int a;};struct b {    struct a;    int b;};int  add(int a, int b){    return a + b;}int main() {    //int sum;    int (*fun)(int, int);    printf("函数add %d\n", add(1, 2));    fun = add;    printf("函数fun %d\n", fun(2, 3));    return 0;}

fun这是函数指针。函数是放在编码中的代码段中,程序直接执行不到那块代码段,内存表示只是数据。汇编中call 函数名,就是跳转到函数体,也就是跳转到代码段。函数指针其实就是指向代码段的指针。

typedef struct B_ {    struct_a a;     int(*fun)(struct_c *c);    int b;    struct_c *c;}struct_b;

3、this指针
书本对this指针的定义:this指针指向不同的对象,因此成员函数set可以对不同的对象的c1,c2进行赋初值。
不同对象其实就是不同的结构体。每个结构体的内存地址不一样,所以肯定不会发生冲突。而创建一个新的对象(struct_b)时候,使用this指针(struct_c )肯定要重新申请空间,所以指向的struct_c 的地址也不一样。所以c1,c2进行赋值的空间也不一样。
这也是成员函数肯定包括this指针,因为缺少指针无法知道分配的空间,struct会分配4个字节的指针空间,但是不会分配具体的地址。this指针是需要申请的,c++中class类的实现,肯定会调用构造函数在初始化对象的时候,申请this指针。这样就形成了接口。

typedef  struct A_{    int a;}struct_a;int add(struct_c *c) {    return c->c1 + c->c2;}void set(struct_c *c,int a, int b) {    c->c1 = a;    c->c2 = b;}typedef struct B_ {    struct_a a;     int(*fun)(struct_c *c);    void(*fun2)(struct_c *c,int a,int b);    int b;    struct_c *c;}struct_b;int main() {    struct_b b_struct;    //b_struct.c = new_c();    b_struct.a.a = 1;    b_struct.b = 3;    b_struct.c = new_c();    b_struct.c->c1 = 1;    b_struct.c->c2 = 2;    b_struct.fun = add;    b_struct.fun2 = set;    b_struct.fun2(b_struct.c,1, 2);    //b_struct.fun(b_struct.c);    printf("%d\n", b_struct.fun(b_struct.c));}

4、go语言的struct
原先我认为go语言肯定是不存在函数指针的,因为它有interface关键字,而且如何在go语言中写函数指针的格式,go肯定是有函数指针的,add := a,add就是函数指针,问题不知道如何声明。

func a(a int, b int) int {    return a + b}func main() {    add := a    //(abb *) func (int,int) int = a//这是错的    fmt.Printf("%v,%d", add, add(1, 2))}

好像又做了一天无用功,和go没有半毛钱关系。就当了解class和struct的关系。
计划:2016年12月21日 go interface;

1 0
原创粉丝点击