如何让 main 成为我班上的朋友?

发布于 2024-12-22 19:24:33 字数 354 浏览 4 评论 0原文

我认为这是可能的,但编译器抱怨它无法访问我的类的受保护/私有成员。我尝试过移动东西并更改签名,但找不到有效的组合。

我基本上有:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

禾厶谷欠 2024-12-29 19:24:33

你所拥有的是正确的。

适用于 GCC 4.3.4

What you have is correct.

Works in GCC 4.3.4

毁虫ゝ 2024-12-29 19:24:33

您可能不应该在这里做您想做的事情——当然有更好的方法。话虽这么说,您可以尝试在全局命名空间 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 ::).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文