如何让 main 成为我班上的朋友?
我认为这是可能的,但编译器抱怨它无法访问我的类的受保护/私有成员。我尝试过移动东西并更改签名,但找不到有效的组合。
我基本上有:
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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你所拥有的是正确的。
适用于 GCC 4.3.4
What you have is correct.
Works in GCC 4.3.4
您可能不应该在这里做您想做的事情——当然有更好的方法。话虽这么说,您可以尝试在全局命名空间
friend int ::main
中声明友元函数(请注意范围解析运算符::
的使用)。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::
).