由于对课本的生疏,就只记得一种结构体初始化方法,那就是定义的时候直接初始化
struct student
{
int num;
double grade;
char name;
} student1;
甚至连
struct student student2; 都忘了,真是猪脑子
今天自己重新温习了一下,记录结构体初始化的三种用法如下:
// TypedefAndStruct.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
struct student
{
int num;
double grade;
char name;
} student1;
typedef struct teacher
{
int num;
char course;
}* PTECH1,* PTECH2, TECH;
typedef struct student ST1;
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"press the student1 name :"<<endl;
cin>>student1.name;
cout<<"press the student1 grade :"<<endl;
cin>>student1.grade;
struct student student2;
cout<<"press the student2 name :"<<endl;
cin>>student2.name;
cout<<"press the student2 grade :"<<endl;
cin>>student2.grade;
ST1 student3;
cout<<"press the student3 name :"<<endl;
cin>>student3.name;
cout<<"press the student3 grade :"<<endl;
cin>>student3.grade;
PTECH1 P_teacher1;
PTECH2 P_teacher2;
TECH teacher1;
cout<<"press teacher number:"<<endl;
cin>>teacher1.num;
cout<<"press teacher taught course:"<<endl;
cin>>teacher1.course;
P_teacher1=& teacher1;
P_teacher2=P_teacher1;
cout<<student1.name<<"'s grade is:"<<student1.grade<<endl;
cout<<student2.name<<"'s grade is:"<<student2.grade<<endl;
cout<<student3.name<<"'s grade is:"<<student3.grade<<endl;
cout<<P_teacher2->num<<"taught couse is:"<<P_teacher2->course<<endl;
system("pause");
return 0;
}
另外还有一种typedef的方法:
typedef struct student
{
int num;
double grade;
char name;
} * p_stu; //p_stu就是student结构体的指针类型了
但是这种定义的时候跟一般的定义有个不同之处,需要注意:
typedef struct teacher
{
int num;
char course;
}* PTECH1,* PTECH2, TECH;//这里的PTECH1和PTECH2 是指针,而TECH却是teacher这个结构体的数据类型,所以有如下用法
PTECH1 P_teacher1;
PTECH2 P_teacher2;
TECH teacher1;
cout<<"press teacher number:"<<endl;
cin>>teacher1.num;
cout<<"press teacher taught course:"<<endl;
cin>>teacher1.course;
P_teacher1=& teacher1;
P_teacher2=P_teacher1;
最近在学数据结构单链表,看到一个类后面使用typedef定义指针类型的时候傻眼了,原来是这个意思
class LinkNode
{
public:
ElemType data;
LinkNode *next;
};
typedef LinkNode * NodePointer;
NodePointer p;//定义了LinkNode 类的指针p