调用main()之外的函数

Call a function outside main ()

本文关键字:函数 main 调用      更新时间:2023-10-16

我正在尝试这样做:

#include <iostream>
using namespace std;
class smth {
  public:
  void function1 () { cout<<"before main";}
  void function2 () { cout<<"after main";}
};
call function1();
int main () 
{
  cout<<" in main";
  return 0;
}
call funtion2();

我想留言:"在main之前"在主体中"在主之后"

我该怎么做?

你不能。至少不是那样。您应该能够通过将代码放入类构造函数和析构函数中,然后声明一个全局变量来解决这个问题:

struct myStruct
{
    myStruct() { std::cout << "Before main?n"; }
    ~myStruct() { std::cout << "After main?n"; }
};
namespace
{
    // Put in anonymous namespace, because this variable should not be accessed
    // from other translation units
    myStruct myStructVariable;
}
int main()
{
    std::cout << "In mainn";
}