How do I call main() in my main cpp file from a seperate cpp file?

前端 未结 5 975
失恋的感觉
失恋的感觉 2021-01-29 14:33

I\'m making a class that displays a message to the user and asks them if they want to return to the start of the program, but the message function is in a separate class from wh

相关标签:
5条回答
  • 2021-01-29 14:45

    In C++ it is illegal for a program to call main itself, so the simple answer is you don't. You need to refactor your code, the simplest transformation is to write a loop in main, but other alternatives could include factoring the logic out of main into a different function that is declared in a header and that you can call.

    0 讨论(0)
  • 2021-01-29 14:45

    Maybe something like that:

    bool dispMessage(void)
    {
      cout << "This is my message" << endl;
      // call me again
      return true;
    
      // do not call me again
      return false;
    }
    

    and in the int main():

    int main()
    {
      Message DisplayMessage;
      while(DisplayMessage.dispMessage())
      {
    
      }
      return 0;
    } 
    
    0 讨论(0)
  • 2021-01-29 14:55

    Assuming that you could change dispMessage(void) to something like bool askForReturnToStart() then you could use that to build a loop within main, f.e.:

    int main() {
      Message dm;
      do {
        // whatever
      } while (dm.askForReturnToStart());
    }
    
    0 讨论(0)
  • 2021-01-29 14:58

    main is special, you're not allowed to call it in C++.

    So the "obvious" thing to do is to move everything to another function:

    int my_main()
    {
        Message DisplayMessage;
        DisplayMessage.dispMessage();
        return 0;
    } 
    
    int main() 
    {
        return my_main();
    }
    

    Now you can call my_main from anywhere you like (as long as you declare it first in the translation unit you want to call it from, of course).

    I'm not sure whether this will really solve your problem, but it's as close as possible to calling main again.

    If you call my_main from somewhere else in your program then you won't exactly be "returning to the start", you'll be starting a new run through the code without having finished the old one. Normally to "return to the start" of something you want a loop. But it's up to you. Just don't come crying to us if you recurse so many times that you run out of stack space ;-)

    0 讨论(0)
  • 2021-01-29 15:08

    you don't, change the return value of dispMessage to an int or similar, from the main you check the return code and do different actions based on that.

    0 讨论(0)
提交回复
热议问题