switch语句
switch语句的语法形式如下:
switch(表达式) {
case 常量表达式1: 语句1
case 常量表达式2: 语句2
...
case 常量表达式n: 语句n
default: 语句n+1
}
需要注意的是:
- switch后面的表达式可以是整型、字符型、枚举型。
- 每个case分支可以有多条语句,且不必使用{ }。
- 每个case分支的语句最后都应该加上break语句,否则会从该case入口点开始一直执行到switch结构的结束点。
- 如果多个case分支执行同样的操作,可以使多个case分支共用一组语句。
看如下的例子
int day;
cin >> day;
switch (day) {
case 1:
cout << "Monday" << endl;
break;
case 2:
cout << "Tuesday" << endl;
break;
case 3:
cout << "Wednesday" << endl;
break;
case 4:
cout << "Thursday" << endl;
break;
case 5:
cout << "Friday" << endl;
break;
case 6:
case 7:
cout << "Weekend" << endl;
break;
default:
cout << "day error" << endl;
}
----------------
输入:1
输出:Monday
输入:6
输出:Weekend
输入:7
输出:Weekend
typedef声明
作用:给某个数据类型起别名。看下面的例子:
//给int数据类型起一个别名,叫做Age
typedef int Age;
class MemberInOrganization {
private:
string name; //记录姓名
string num; //记录编号
Age age; //记录年龄
public:
MemberInOrganization(string name, string num, Age age) {
this->name = name;
this->num = num;
this->age = age;
}
void printMemberInfo() {
cout << "name: " << name << endl;
cout << "num: " << num << endl;
cout << "age: " << age << endl;
cout << endl;
}
};
int main() {
//学生和工人都可以用MemberInOrganization类的对象表示,
//所以给MemberInOrganization类起2个别名,分别是Student和Worker。
typedef MemberInOrganization Student, Worker;
Student stu("jack", "001", 20);
Worker worker("sam", "002", 35);
stu.printMemberInfo();
worker.printMemberInfo();
return 0;
}
----------------
输出结果为:
name: jack
num: 001
age: 20
name: sam
num: 002
age: 35
枚举类型enum
枚举类型的声明格式为:
enum Weekly {SUN, MON, TUE, WED, THU, FRI, SAT};
说明:
- 枚举元素按常量处理,不能对其赋值。即
SUN = 0
这条语句是非法的。 - 枚举元素具有默认值,依次为:0,1,2,… 。上面的例子中,SUN的值为0,MON的值为1,…,SAT的值为6。
- 可以在声明的时候另行定义枚举元素的值,如
enum Weekly {SUN = 3, MON = 2, TUE, WED, THU, FRI, SAT};
//SUN的值为3,MON的值为2,TUE的值为3,WED的值为4,依次加1,SAT的值为7
- 枚举值可以进行关系运算,因为它本来就是整数。
- 整数值不能直接赋值给枚举变量(可以强制类型转换之后赋值给枚举变量)。枚举型数据可以隐含转换为整型数据。
枚举类型使用的示例如下:
enum GameResult (WIN, LOSE, TIE, CANCEL); //定义了四种结果,WIN的值为0,LOSE的值为1,TIE的值为2,CANCEL的值为3
int main() {
GameResult result; //声明枚举变量时,可以不写关键字enum
enum GameResult omit = CANCEL; //也可以写上enum关键字
for (int count = WIN; count <= CANCEL; count++) { //WIN隐式转换为int类型;枚举类型可以进行关系比较
result = GameResult(count); //int类型数据显式转换为枚举类型
if (result == omit) //枚举类型可以进行关系比较
cout << "The game was cancelled" << endl;
else {
cout << "The game was played ";
if (result == WIN)
cout << "and we won!";
if (result == LOSE)
cout << "and we lost.";
cout << endl;
}
}
return 0;
}
--------------
输出结果为:
The game was played and we won!
The game was played and we lost.
The game was played
The game was cancelled