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

和自甴很熟 提交于 2019-12-23 11:47:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!