【问题标题】:How do I make a function execute a task when it ends?如何让函数在结束时执行任务?
【发布时间】:2021-12-03 07:43:50
【问题描述】:

我有一个函数,只要满足条件,我希望它被无限调用。但是,我不能简单地在其内部调用该函数,因为这会导致堆栈溢出。如何在结束函数的同时启动另一个函数?

例子:

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();
    }
}

【问题讨论】:

  • 问:你的程序是否block直到条件满足?如果是这样,只需调用您的函数。问:否则,您的操作系统是什么?理想情况下,您可以阻止一些“信号”。确切地说,您将如何执行此操作取决于操作系统。注意:您可以做的 WORST 是poll。请尽量避免“投票”!

标签: c++ function recursion


【解决方案1】:
int myFunc() {
  char again;
  do {
    std::cout << "Do it again?\n";
    std::cin >> again;
    
  } while (again == 'y');
}

【讨论】:

    【解决方案2】:

    好吧,你没有给出任何代码示例,所以我可能在这里有点困难,但我猜你有这样的东西:

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2018-04-08
      • 1970-01-01
      • 2023-03-21
      • 2021-03-20
      相关资源
      最近更新 更多