加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

同伴之间的C友谊健康吗?

发布时间:2020-12-16 10:55:19 所属栏目:百科 来源:网络整理
导读:虽然阶级友谊是C的最后一个度假胜地,但这种模式是否有意义? class Peer{public: friend class Peer; void GetSecret(const Peer other) { const std::string secret = other.GiveSecret(); std::cout secret std::endl; }private: const std::string GiveSe
虽然阶级友谊是C的最后一个度假胜地,但这种模式是否有意义?

class Peer
{
public:
    friend class Peer;
    void GetSecret(const Peer& other)
    {
        const std::string& secret = other.GiveSecret();
        std::cout << secret << std::endl;
    }

private:
    const std::string& GiveSecret() const
    {
        return "secrety stuff";
    }
};

int main(int argc,char* argv[])
{
    Peer peerA;
    Peer peerB;
    peerA.GetSecret(peerB);
    return 0;
}

好的,这种模式的原因是因为对等体都是相同的等级,并且他们需要彼此分享知识,但是这种知识是秘密的,因为除了对等体之外没有人应该使用它,或者程序不再有效.

一个非常真实的例子是,当一个对等体从另一个对等体复制构建时,它需要从其源对等体访问秘密信息,但同样没有其他人知道这些内部对象,只有对等体.

解决方法

在这种情况下,朋友不是必需的.类的对象可以访问任何其他相同类型的对象的私有成员.没有朋友声明它应该工作得很好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读