繁体   English   中英

朋友函数在结构中有什么用?

[英]What's the use of a friend function in a struct?

我正在使用以下语法在结构内重载插入运算符(<<):

struct Address{
    string street;
    string cross;
    int suite;

    friend ostream &operator <<(ostream &oss, const Address &other){
        oss<<"street: "<<other.street<<"cross: "<<other.cross<<"suite: "<<other.suite;
        return oss;
    }
};

我看到只有将函数声明为“地址”结构的朋友,我的代码才会编译。 根据我的理解,当需要访问类的私有成员时,朋友功能非常有用。 但是,由于在结构中所有成员都是公开的,因此无需将'<<'运算符声明为朋友。

有人可以说明是否需要在这里将“ <<”运算符声明为结构“地址”的朋友吗?

实际上,可以在没有friend情况下在命名空间范围内定义该运算符。

在这种情况下,由于给出的确切原因,您不需要“使其成为friend ”,因此不清楚您在哪里听说过!

struct Address
{
   string street;
   string cross;
   int suite;
};

inline ostream& operator<<(ostream& oss, const Address& other)
{
   oss << "street: " << other.street << "cross: " << other.cross << "suite: " << other.suite;
   return oss;
}

(我假设您将整个定义保留在标头中进行了inline ,尽管实际上我可能会在标头中声明它,然后在其他地方定义它。)

但是,用struct定义的类仍然只是一个类,并且仍然可以包含private成员。 如果您有这样做的话,您将再次需要一个friend

某些人可能会选择始终使之成为friend函数以保持一致性,因此,当您阅读operator<<它的定义看起来像是在类中。 另外,可能有些奥秘的查找约束使此操作变得很方便(因为以这种方式定义的friend功能只能由ADL找到),尽管我想不起。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM