简体   繁体   English

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

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

I'm overloading the insertion operator (<<) inside a struct using the following syntax: 我正在使用以下语法在结构内重载插入运算符(<<):

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

I see that only if I declare the function as a friend of struct 'Address' does my code compile. 我看到只有将函数声明为“地址”结构的朋友,我的代码才会编译。 As per my understanding a friend function is useful when there's a need to access the private members of a class. 根据我的理解,当需要访问类的私有成员时,朋友功能非常有用。 But, since in a struct all the members are public, there shouldn't be a need to declare the '<<' operator as a friend. 但是,由于在结构中所有成员都是公开的,因此无需将'<<'运算符声明为朋友。

Could anybody please clarify the need of declaring '<<' operator here as a friend of the struct 'Address'? 有人可以说明是否需要在这里将“ <<”运算符声明为结构“地址”的朋友吗?

Indeed, that operator can be defined at namespace scope without friend . 实际上,可以在没有friend情况下在命名空间范围内定义该运算符。

You do not "need" to make it a friend in this case, for exactly the reasons you give, so it's not clear where you've heard that you do! 在这种情况下,由于给出的确切原因,您不需要“使其成为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;
}

(I made it inline on the assumption you're keeping the whole definition in the header, though in reality I'd probably declare it in the header then define it elsewhere.) (我假设您将整个定义保留在标头中进行了inline ,尽管实际上我可能会在标头中声明它,然后在其他地方定义它。)

However a class defined with struct is still just a class and can still contain private members just fine. 但是,用struct定义的类仍然只是一个类,并且仍然可以包含private成员。 If you had one that did, you would once again need a friend . 如果您有这样做的话,您将再次需要一个friend

Some people may choose to always make a friend function for consistency, and so that the definition of operator<< looks like it's "in" the class when you read it. 某些人可能会选择始终使之成为friend函数以保持一致性,因此,当您阅读operator<<它的定义看起来像是在类中。 Alternatively there may be some arcane lookup constraints that make this convenient (since a friend function defined in this way can only be found by ADL), though I can't think of any off the top of my head. 另外,可能有些奥秘的查找约束使此操作变得很方便(因为以这种方式定义的friend功能只能由ADL找到),尽管我想不起。

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

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