结构中的友元函数有什么用?
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;
}
};
我看到只有当我将该函数声明为结构"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 找到),尽管我想不出任何超出我的头顶。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 当在同一名称空间中有两个具有相同签名的函数时,会发生什么
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 什么时候调用析构函数
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 是什么原因导致它无法编译?它是声明签名还是在函数本身的实现中
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 是什么让放置新调用对象的构造函数?
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 在C 中,对2D数组的增量是什么?函数断言(0)做什么?
- 我应该使用什么函数签名来返回对可能不存在的对象的引用
- 一个类的构造函数,为另一个类进行强制转换.将调用什么函数
- 在 opencv for c 中,什么函数与 Mat::convertTo 和 cvtColor() 完全相同
- 当按下Alt-Enter键时调用什么函数
- C库导出什么函数?
- 使用什么函数来选择文本
- c++在空类中编写和调用什么函数?
- 在共享库的构造函数(_init部分)中,如何知道什么函数被中断了?
- 我可以用什么函数来获取按钮的把手