问题
I'm thinking this is possible, but the compiler is complaining it cannot access the protected/private members of my class. I've tried moving stuff around and changing signatures, but can't find a combination that works.
I essentially have:
class MyClass
{
public:
friend int main(int argc, char** argv);
private:
void test()
{
cout << "My friend has accessed my member" << endl;
}
};
int main(int argc, char** argv)
{
MyClass mc;
mc.test();
}
回答1:
What you have is correct.
Works in GCC 4.3.4
回答2:
You probably shouldn't do what you're trying to do here -- there is certainly a better way. That being said, you could try declaring the friend function in the global namespace, friend int ::main
(note the use of the scope resolution operator ::
).
来源:https://stackoverflow.com/questions/8619133/how-do-i-make-main-a-friend-of-my-class