您正在尝试做的 - 在函数之间跳转 - 由于一系列原因(尤其是对象范围和生命周期)无效,请考虑:
void foo()
{
if(feelLikeIt)
goto foobar;
}
void bar()
{
std::string message = "Hello";
foobar:
cout << message << endl;
}
从 foo 跳转到 foobar 是非法的,因为“消息”将不存在。
所以简单的语言不允许你这样做。
此外,您尝试使用“goto”的方式会阻止您重新使用“fruit()”函数,因为它总是决定如何处理选择而不是调用它的函数。如果你想这样做怎么办:
cout<<"What do you want to eat? (a/b)";
fruit();
foo: cout<<"You eat an apple.";
fooo: cout<<"You eat a banana.";
cout<<"What does your friend want to eat? (a/b)";
fruit();
// oops, you just created a loop because fruit made the decision on what to do next.
您实际上想要做的是使用“fruit()”作为返回值的函数。
enum Fruit { NoSuchFruit, Apple, Banana };
Fruit fruit(const char* request)
{
char foodstuffs;
cout << request << " (a/b)";
cin >> foodstuffs;
switch (foodstuffs)
{
case 'a': return Apple;
case 'b': return Banana;
default:
cout << "Don't recognize that fruit (" << foodstuffs << ")." << endl;
return NoSuchFruit;
}
}
const char* fruitNames[] = { "nothing", "an apple" ,"a banana" };
int main()
{
Fruit eaten = fruit("What do you want to eat?");
cout << "You ate " << fruitNames[eaten] << "." << endl;
eaten = fruit("What does your friend want to eat?");
cout << "Your friend ate " << fruitNames[eaten] << "." << endl;
}