簡體   English   中英

如何讓函數在結束時執行任務?

[英]How do I make a function execute a task when it ends?

我有一個函數,只要滿足條件,我就希望無限調用它。 但是,我不能簡單地在其內部調用該函數,因為這會導致堆棧溢出。 如何結束該功能並同時啟動另一個功能?

例子:

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();
    }
}
int myFunc() {
  char again;
  do {
    std::cout << "Do it again?\n";
    std::cin >> again;
    
  } while (again == 'y');
}

好吧,您還沒有給出任何代碼示例,所以我可能在這里猶豫不決,但我猜您有這樣的事情:

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
    // ...
}
  1. (更好的是,您只需編輯 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM