在Form.h中,我有:
enum Direction {
NORTH = 0,
SOUTH = 1,
EAST = 2,
WEST = 3,
};
在Play.cpp中我有一个方法可以打印出类似" PlayerA移动到NORTH"
的运动void Play::printMove(Direction dir) {
std::cout << this->getName() << " moved to " << dir << std::endl;
}
因为这打印了0,1,2或3我尝试过:
void Play::printMove(Direction dir) {
std::string moveStr;
switch (dir) {
case NORTH: moveStr = "NORTH";
case SOUTH: moveStr = "SOUTH";
case EAST: moveStr = "EAST";
case WEST: moveStr = "WEST";
}
std::cout << this->getName() << " moved to " << moveStr << std::endl;
}
但这也没有奏效。为什么?我该怎么办?
答案 0 :(得分:0)
您需要break
关键字,否则printMove()
将始终生成“WEST”。一旦计算机找到匹配的案例,它就会一直读取switch
语句后面的代码。 break
关键字告诉计算机停止阅读并在switch
的结束括号后继续执行该程序。
void Play::printMove(Direction dir) {
std::string moveStr;
switch (dir) {
case NORTH:
moveStr = "NORTH";
break;
case SOUTH:
moveStr = "SOUTH";
break;
case EAST:
moveStr = "EAST";
break;
case WEST:
moveStr = "WEST";
break;
}
std::cout << this->getName() << " moved to " << moveStr << std::endl;
}