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

Shu*_*ade 1 c++ struct friend c++11

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

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

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

有人可以澄清是否需要在这里声明'<<'运算符作为结构'地址'的朋友?

Lig*_*ica 7

实际上,可以在命名空间范围内定义该运算符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;
}
Run Code Online (Sandbox Code Playgroud)

(我inline假设您将整个定义保留在标题中,但实际上我可能会在标题中声明它然后在别处定义它.)

但是,定义的类struct仍然只是一个类,并且仍然可以包含private成员.如果你有一个,你会再次需要一个friend.

有些人可能会选择始终使friend函数保持一致性,因此operator<<当您阅读它时,它的定义看起来像是在"类"中.或者,可能存在一些神秘的查找约束,这使得这很方便(因为friend以这种方式定义的函数只能由ADL找到),尽管我无法想到任何偏离我的头脑.