`
3895177
  • 浏览: 22639 次
社区版块
存档分类
最新评论

自定义数据类型

    博客分类:
  • c++
 
阅读更多

定义和使用结构.cpp

 

#include <iostream>
#include <string>
using namespace std;

struct Student
{
	int nID;
	char szName[20];
	char szAddr[100];
	char szPhone[15];
	float fScore;
};

void main()
{
	//据说此时候s的值是随机的...但是编译不通过
	//Student s;
	
	//声明的时候可以这样赋值,非声明的地方不能这样赋值
	Student  S = {1,"李明","解放路85号","12345678912345",93.5};

	Student s;
	s.nID = 1;
	strcpy(s.szName,"李明");
	strcpy(s.szAddr,"解放路85号");
	strcpy(s.szPhone,"12345678912345");
	s.fScore = 93.5;


	cout<<s.nID<<endl;
	cout<<s.szName<<endl;
	cout<<s.szAddr<<endl;
	cout<<s.szPhone<<endl;

	//结构与指针
	Student* ps = &s;

	strcpy(ps->szAddr,"火星");
	
	cout<<s.szAddr<<endl;

	
}

 枚举类型.cpp

#include <iostream>
using namespace std;

enum Test{
	t0,
	t1,
	t2 = 3,
	t3,
};

void pintInfo(Test t);

void main()
{
	Test t = t0;
	//从0开始,t = 0
	cout<<t<<endl;
	t = t1;
	//下一个自动+1,现在t=1
	cout<<t<<endl;
	t = t2;
	//因为设定了t2=3,所以现在t = 3
	cout<<t2<<endl;
	t=t3;
	//下一个自动+1,现在t=4
	cout<<t3<<endl;

	//输出“现在是t3”
	pintInfo(t);
	

}

void pintInfo(Test t)
{
	switch(t)
	{
	case t0:
		cout<<"现在是t0"<<endl;
		break;
	case t1:
		cout<<"现在是t1"<<endl;
		break;
	case t2:
		cout<<"现在是t2"<<endl;
		break;
	case t3:
		cout<<"现在是t3"<<endl;
		break;
	}
}

 用typedef声明类型.cpp

#include <iostream>
using namespace std;

//用typedef 来给tagStudent定义别名
typedef struct tagStudent
{
	int nID;
	char szName[20];
	char szAddr[100];
	char szPhone[15];
	float fScore;
}Student,*PStudent;
//给tagStudent定义了一个Student的别名和一个PStudent的指针别名
void main()
{
	tagStudent s;
	tagStudent* ps;
	//等价于
	Student s;
	//因为PStudent是指针类型,所以s不需要加*
	PStudent s; 	
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics