学习了C++中的类,就觉得结构体好像更亲切一些了,所以这边将结构体进行总结下:
常常使用的结构体的用法:
第一种:
#include <iostream>
#include <stdio.h>
using namespace std;
//定义结构体的名称为A
struct A
{
char a;
int b;
double c;
};
void main()
{
A a1; //创建对象进行调用
cout << sizeof(a1.a) << endl;
cout << sizeof(a1.b) << endl;
cout << sizeof(a1.c) << endl;
//cout << sizeof(A::a) << endl;//错误的,只能通过对象来进行调用
//不能通过结构体的名称来直接进行调用
while (1);
}
第二种常见的表示方式:
#include <iostream>
#include <stdio.h>
using namespace std;
typedef struct A
{
char a;
int b;
double c;
}B1;
void main()
{
B1 b1;//重命名为B1,并创建对象
A a1;//原先的名字是A,创建对象
cout << sizeof(b1.a) << endl;
cout << sizeof(b1.b) << endl;
cout << sizeof(b1.c) << endl;
//cout << sizeof(B1::a) << endl;error,不能直接通过名字来访问
//cout << sizeof(B1.a) << endl; //error,这种访问因为有了typedef这句,所以也是不能用的
cout << sizeof(a1.a) << endl;
cout << sizeof(a1.b) << endl;
cout << sizeof(a1.c) << endl;
//cout << sizeof(A::a) << endl;//error,不能通过名字来进行直接访问
while (1);
}
不常用的:第三种用法:
#include <iostream>
#include <stdio.h>
using namespace std;
struct A
{
char a;
int b;
double c;
}B1;
void main()
{
cout << sizeof(B1.a) << endl;//没有创建对象,直接进行调用的,这种方法比较奇特
cout << sizeof(B1.b) << endl;//但是这种用法一旦在开始的时候加上typedef就会报错
cout << sizeof(B1.c) << endl;
//cout << sizeof(A.a) << endl;error,这种用法也是不允许的
//cout << sizeof(A.b) << endl;
// cout << sizeof(A.c) << endl;
while (1);
}
参考了博客:https://blog.csdn.net/dawn_after_dark/article/details/73555562进行改编