C++自定义数据类型(谭浩强7.5-7.7)

例7.5 用结构体变量作函数参数

#include <iostream>
#include <string>
using namespace std;
struct Student //声明结构体类型
{
	int num;
	string name;//此处原文是char编译出错,改为string编译正确
	float score[3];
};
int main()
{
	void print(Student);//函数声明形参为结构体Student
	Student stu;//定义结构体变量
	stu.num = 12345;
	stu.name = "Li Fang";
	stu.score[0] = 67.5;
	stu.score[1] = 89;
	stu.score[2] = 78.5;
	print(stu);//调用print成员函数,输出stu各成员值
	return 0;
}
void print(Student stu)
{
	cout << stu.num << " " << stu.name << " " << stu.score[0] <<
		" " << stu.score[1] << " " << stu.score[2] << endl;
}

执行效果如图:
在这里插入图片描述
例7.5还可以使用指向结构体变量的指针做实参

#include <iostream>
#include <string>
using namespace std;
struct Student //声明结构体类型
{
	int num;
	string name;//此处原文是char编译出错,改为string编译正确
	float score[3];
}
stu = {12345,"Li Fang",67.5,89,78.5};//定义结构体Student变量stu,并赋初值
int main()
{
	void print(Student*);//函数声明形参为指向Student类型数据的指针变量
	Student *pt=&stu;//定义基类型为Student的指针变量pt,并指向stu
	print(pt);//实参为指向结构体变量stu指针变量
	return 0;
}
void print(Student *p)//定义函数及形参为Student的指针变量
{
	cout << p->num << " " << p->name << " " << p->score[0] <<
		" " << p->score[1] << " " << p->score[2] << endl;
}

上例还可以使用结构体变量的引用作函数参数

#include <iostream>
#include <string>
using namespace std;
struct Student //声明结构体类型
{
	int num;
	string name;//此处原文是char编译出错,改为string编译正确
	float score[3];
}
stu = {12345,"Li Fang",67.5,89,78.5};//定义结构体Student变量stu,并赋初值
int main()
{
	void print(Student&);//函数声明,结构体Student的引用声明
	print(stu);//实参为结构体Student变量
	return 0;
}
void print(Student &stu)//定义函数及形参为Student的引用
{
	cout << stu.num << " " << stu.name << " " << stu.score[0] <<
		" " << stu.score[1] << " " << stu.score[2] << endl;
}

例7.7 枚举类型enum(enum为常量const)
有五种颜色的球,得到三种颜色不同的球的取法:

#include <iostream>
#include<iomanip>
#include <string>
using namespace std;
int main()
{
	enum color{red,yellow,blue,white,black};
	color pri;
	int i, j, k, n = 0, loop;
	for (i = red; i <= black; i++)
		for (j = red; j <= black;j++)
			if (i != j)
			{
		for (k = red; k <= black;k++)
			if ((k != i) && (k != j))
			{
			n = n + 1;
			cout << setw(3) << n;
			for (loop = 1; loop <= 3; loop++)
			{
				switch (loop)
				{
				case1:pri = color(i); break;
				case2:pri = color(j); break;
				case3:pri = color(k); break;
				default:break;
				}
			switch (pri)
				{
				case red:cout<<setw(8)<<"red"; break;
				case yellow:cout << setw(8) << "yellow"; break;
				case blue:cout << setw(8) << "blue"; break;
				case white:cout << setw(8) << "white"; break;
				case black:cout << setw(8) << "black"; break;
				default:break;
				}
			}
			cout << endl;
			}
			}
	cout << "total:" << n << endl;
	return 0;
}

运行出错,待检查!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值