C++ 为什么在这个switch语句之后没有执行代码?
由于某些原因,在main()中的C++ 为什么在这个switch语句之后没有执行代码?,c++,switch-statement,C++,Switch Statement,由于某些原因,在main()中的tulip.flowerHealth()之后没有执行任何操作。我是否对开关盒做了一些错误的操作,或者我是否创建了错误的对象 main.cpp #include <iostream> #include "flower.h" using namespace std; int main() { flower tulip; int i = 1; cout << "Press 1 to water. Press 2 to
tulip.flowerHealth()之后没有执行任何操作。我是否对开关盒做了一些错误的操作,或者我是否创建了错误的对象
main.cpp
#include <iostream>
#include "flower.h"
using namespace std;
int main()
{
flower tulip;
int i = 1;
cout << "Press 1 to water. Press 2 to do nothing." << endl;
while( tulip.curWater() > 0 && tulip.curWater() < 6 ){
cin >> i;
if ( i == 1){
tulip.water();
} else {
tulip.dry();
}
cout << "Flower water level is: " << tulip.curWater() << " " << tulip.flowerHealth() << endl;
} // end of while loop
cout << "Your flower has died. :(" << endl;
return 0;
}
有根据的猜测:curWater()
返回数字1到5以外的值flowerHealth()
然后到达右大括号,但没有遇到return
语句,这是声明为返回除void
之外的其他内容的函数的未定义行为。flowerHealth()
的返回值未定义,如果curWater()
未返回1到5之间的值。想象一下,如果main()
循环看到curWater()
为1并调用dry()
,或者看到curWater()
为5并在调用flowerHealth()
时调用water()
-未定义的行为,会发生什么!你确定不是在等你的输入吗?您在循环开始时获取输入,但仅在循环外部进行提示。如果您从2
开始,并且没有超出边界,则程序对我来说可以正常工作。如果以1
开头,则会出现故障。不清楚为什么您会提示“1去浇水,2什么也不做”,但对于输入1,您会调用dry()
,对于输入2,您会调用water()
@RemyLebeau-Perfect,谢谢。你说得对,我不在开关箱的范围之内。
#ifndef FIRSTPROJ_FLOWER_H
#define FIRSTPROJ_FLOWER_H
#include <string>
using namespace std;
class flower
{
public:
string flowerHealth();
int curWater();
void water();
void dry();
int waterLvl = 1;
};
#endif //FIRSTPROJ_FLOWER_H
#include "flower.h"
int flower::curWater(){
return waterLvl;
}
void flower::water(){
waterLvl++;
};
void flower::dry() {
waterLvl--;
};
string flower::flowerHealth(){
switch(curWater()){
case 1 : return "Flower desperately needs water!";
case 2 : return "Flower is doing alright.";
case 3 : return "Optimal water for the flower to grow.";
case 4 : return "Flower is doing alright.";
case 5 : return "Flower is being over watered!";
}
}