Zexin Li

Please keep honest, open, patient, happy and visionary.

0%

c++的struct和class(重新发布)

总述

在学习c++的时候会遇到一个问题:什么时候使用struct,什么时候使用class?

C的struct

1
2
3
4
5
6
struct tag { 
member1;
member2;
member3;
...
} variable;

tag 是结构体标签。
member 是标准的变量定义,比如 int i; 或者 float f; 或者其他有效的变量定义。
variable 结构变量,定义在结构的末尾,最后一个分号之前,可以指定一个或多个结构变量。
一般情况下,上述三个变量至少要出现2个。

struct不能给内部变量初始化。
值得一提的是,在C中struct是用来封装数据的(member可以包含一个或多个基本数据类型,也可以包含其它结构体),但是其中不能够有成员函数。

想要C语言中的struct中包含成员函数,只能通过函数指针去替代成员函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

void test(int input) {
printf("%d",input);
}
typedef struct _tag {
void (*func)(int);
} Tag;

int main(void)
{
Tag tag;
tag.func = &test;
tag.func(0);
return 0;
}

C++的struct

C++的struct和class的关联

回到正题,c++中继承了在c语言中的用法,但是又做了改进:可以包含成员函数。从可实现功能上来看,struct和class基本上没有什么区别了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>

typedef struct _tag {
void func(int input) {
printf("%d",input);
};
} Tag;

int main(void)
{
Tag tag;
tag.func(0);
return 0;
}

// 令人疑惑的是,在mac环境下居然这段代码用gcc编译也通过了,还能正常运行。
// 应当在ubuntu环境下是不能编译通过的。

C++的struct和class的区别

默认修饰符:struct是public,class是private。以下的代码从逻辑上是等价的:

1
2
3
4
5
6
7
8
9
10
11
class A {
int A_a;
public:
int A_b;
};

struct B {
int B_b;
private:
int B_a;
};

默认继承方式是:struct是public继承,class是private继承。建议在继承时需要显示地指明修饰符。

1
2
3
4
5
6
7
8
9
10
11
12
class A {
int A_a;
public:
int A_b;
};

struct B : public A {
// 建议在继承时需要显示地指明修饰符
int B_b;
private:
int B_a;
};

Welcome to my other publishing channels