我有一個函式,只要滿足條件,我就希望無限呼叫它。但是,我不能簡單地在其內部呼叫該函式,因為這會導致堆疊溢位。如何結束該功能并同時啟動另一個功能?
例子:
int myFunc() {
//do stuff
char again;
std::cout << "Do it again?\n";
std::cin >> again;
//I want to do this, but in a way that ends the function first.
if (again = y) {
myFunc();
}
}
uj5u.com熱心網友回復:
好吧,您還沒有給出任何代碼示例,所以我可能在這里猶豫不決,但我猜您有這樣的事情:
void my_func()
{
// do stuff
// ...
while (cond)
{
my_func();
}
}
有兩種方法可以解決這個問題:
1)
// this is wherever you call my_func
void some_other_func()
{
while (cond)
{
my_func();
}
}
void my_func()
{
// do stuff
// ...
}
- (更好的是,您只需編輯 my_func 即可呼叫實際方法部分的私有實作)
void my_func_impl()
{
// do stuff
// ...
}
void my_func()
{
while (cond)
{
my_func_impl();
}
}
編輯
現在您發布了一個示例,這就是我重構您的代碼以實作此目的的方式:
void doIt() {
// do stuff
}
void myFunc() {
//do stuff
char again;
while (1) {
std::cout << "Do it again?\n";
std::cin >> again;
if (again = y) {
doIt();
}
// if the answer wasn't yes, the if case won't enter
// break the loop in that case
break;
}
}
uj5u.com熱心網友回復:
int myFunc() {
char again;
do {
std::cout << "Do it again?\n";
std::cin >> again;
} while (again == 'y');
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/318473.html
