typedef struct与struct的区别

737 阅读1分钟

1.定义:

struct:用来定义一个结构体;

typedef:用来类型换名;

typedef struct表示将定义后的结构体定义成想要的类型名;

2.举例:

(1)代码:

#include<iostream>
using namespace std;
typedef int Int32;//将int类型名等价定义成Int32,后续二者均可以表示int型用来定义整形变量

struct HuffmanCode {//定义一个结构体类型
	char c;
	Int32 num;
};

typedef HuffmanCode Code;//将HuffmanCode类型名等价定义成Code,后续二者均可以表示HuffmanCode类型用来定义结构体变量



typedef struct student {//定义一个结构体类型,同时将student类型名等价定义成stu,后续二者均可以表示student类型用来定义结构体变量
	string name;
	long Id;
}stu;


typedef struct teacher {//定义一个结构体类型,未做类型名等价定义
	string name;
	long Id;
};

void main()
{
	Code H = { 'A',5 };
	HuffmanCode C = { 'B',2 };
	cout << H.c << "\t" << H.num << endl;
	cout << C.c << "\t" << C.num << endl;
	C = H;//将变量H的值赋值给C
	cout << C.c << "\t" << C.num << endl;

	stu A = { "CSS",20152000 };
	student B = { "CYR",20150000 };
	cout << A.name << "\t" << A.Id << endl;
	cout << B.name << "\t" << B.Id << endl;
	A = B;//将变量B的值赋值给A
	cout << A.name << "\t" << A.Id << endl;

	teacher T = { "ZHX",14234353 };
	cout << T.name << "\t" << T.Id << endl;
}

(2)测试截图:

image.png