我正在尝试这样做:
#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();
我希望收到此消息: “在主要之前” “在主要” “主要之后”
我该怎么做?
答案 0 :(得分:9)
你做不到。至少不那样。您应该能够通过将代码放在类构造函数和析构函数中来解决它,然后声明一个全局变量:
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 main\n";
}