Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make main a friend of my class? [closed]

Tags:

c++

main

friend

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();
}
like image 343
Jaime Avatar asked Dec 23 '11 17:12

Jaime


2 Answers

What you have is correct.

Works in GCC 4.3.4

like image 197
Peter Alexander Avatar answered Oct 05 '22 23:10

Peter Alexander


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 ::).

like image 37
bobbymcr Avatar answered Oct 05 '22 23:10

bobbymcr