例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;
}
运行出错,待检查!