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

2019-03-07 04:36发布

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 where my main() is located. How do I access the main() function from a different class?

This is an example of the stuff I want to do:
main.cpp file:

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

Message.cpp file:

void dispMessage(void)
{
    cout << "This is my message" << endl;
    //now how do I call main again in the main.cpp file?
}

Thanks!

5条回答
等我变得足够好
2楼-- · 2019-03-07 05:16

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;
} 
查看更多
冷血范
3楼-- · 2019-03-07 05:18

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.

查看更多
仙女界的扛把子
4楼-- · 2019-03-07 05:19

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

查看更多
Animai°情兽
5楼-- · 2019-03-07 05:29

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.

查看更多
Lonely孤独者°
6楼-- · 2019-03-07 05:39

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());
}
查看更多
登录 后发表回答