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

前端 未结 5 977
失恋的感觉
失恋的感觉 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: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 ;-)

提交回复
热议问题