结构中的友元函数有什么用?

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

本文关键字:什么 函数 友元 结构      更新时间:2023-10-16

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

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;
    }
};

我看到只有当我将该函数声明为结构"Address"的好友时,我的代码才会编译。根据我的理解,当需要访问类的私有成员时,朋友函数很有用。但是,由于结构中的所有成员都是公共的,因此不需要将"<<"运算符声明为友元。

任何人都可以澄清在这里声明"<<"运算符作为结构"地址"的朋友的必要性吗?

实际上,可以在命名空间范围内定义该运算符而无需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 找到),尽管我想不出任何超出我的头顶。