C和C++中struct使用的区别
来源:互联网 发布:红蜘蛛软件卸载不了 编辑:程序博客网 时间:2024/04/30 20:32
今天参看了louden用c编写的编译器,发现其中一些地方使用struct很奇妙。所以又研究了一下struct的区别,并发现c和c++在某些地方是有区别的。
struct作为类的一种特例,是用来自定义数据结构的,在编程的过程中是很有用的。C和C++的主要区别是:一个结构标记声明后,C语言必须在结构标记前加上struct才能作为结构类型名,而C++语言中,结构标记可以直接作为结构类型名使用。此外,结构在C++中被作为类的一种特例,并且在结构中,数据成员和成员函数默认的访问权限是共有的,儿类的则是私有的。
首先我们先在C中使用struct:
按照上面的叙述,我很自然的如下书写:
struct Student{
int a;
int b;
};
int main(){
struct Student st;
st.a = 90;
st.b = 80;
printf("%d",st.a);
}
如果我把struct去掉的话那么编译器就会报错(编译器使用的是vc 6.0),说Student是未声明的标识符。但是在c++中就不用担心这一点。如下:
#include<iostream>
using namespace std;
struct Student{
int a;
int b;
};
int main(){
Student st;
st.a = 90;
st.b = 80;
cout<<st.a<<endl;
Student tems = st;
cout<<tems.a<<endl;
return 0;
}
编译器不会报错。从上述的程序中我们还可以看到,struct在C和C++中可以实现各个变量之间的赋值,也就是说不用重载赋值操作符。
那么在C中我可不可以把struct给去掉呢?当然可以,你可以这么做:
typedef struct student{
int a;
int b;
} Student;
int main(){
Student st;
st.a = 90;
st.b = 80;
printf("%d",st.a);
}
使用typedef即可实现上述要求。
++++++++++++++++++++++++++++++++++++++++++++++++++++++
在C和C++中struct和union是非常相似的,只不过union共享存储区而已,共享的是数据变量所占空间最大的存储区。其他和struct一样,都如上所述:
union Student{
int a;
int b;
};
int main(){
union Student st;
st.a = 90;
st.b = 80;
printf("%d",st.a);
}
输出结果是80
C++:
#include<iostream>
using namespace std;
union Student{
int a;
int b;
};
int main(){
Student st;
st.a = 90;
st.b = 80;
cout<<st.a<<endl;
Student tems = st;
cout<<tems.a<<endl;
return 0;
}
输出结果是80 80,从中可以看出它也重载了=操作符。
- C和C++中struct使用的区别
- C 和 C++中struct 的区别
- C和C++中struct的区别
- C#中struct和C中的struct的一个区别
- C语言中struct和typedef struct的区别
- C/C++中typedef struct和struct的区别
- C与C++中struct使用的区别
- C与C++中struct使用的区别
- typedef struct 在C和C++中用法的区别
- C语言中struct和union的区别是什么
- C和C++中typedef struct的区别
- c与c++中enum和struct定义的区别
- C和C++中struct区别
- struct关键字在C和C++中使用时的一点区别
- 在C和C++中struct和typedef struct的区别
- C与C++中struct的区别
- C C++中struct的区别
- 浅析c/c++中 struct的区别
- UE4 Persona:骨架网格物体动画
- OSChina Maven使用说明
- 来自Uber的12条架构重构经验
- jquery根据name取值
- 双击锁定,单击排序的js实现
- C和C++中struct使用的区别
- 深入理解Java:类加载机制及反射
- 【Mongodb】3.0 配置身份验证db.createUser()说明
- Linux服务器显示磁盘满,但实际应用所占不多
- 【转】Vector与ArrayList区别
- 1-题目1202:排序
- 常用MIME类型(Flv,Mp4的mime类型设置)
- Android中简单的图形处理
- 测试