我使用以下语法在结构中重载插入运算符(<<):
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'的朋友时才会编译我的代码.根据我的理解,当需要访问类的私有成员时,友元函数很有用.但是,因为在结构中所有成员都是公共的,所以不应该将'<<'运算符声明为朋友.
有人可以澄清是否需要在这里声明'<<'运算符作为结构'地址'的朋友?