我们想实现一个功能,分别有两个类,一个名为 Sender,负责发送邮件。另外一个类名为 Mail,负责管理发送的标题和内容。在使用的时候,我们需要让类 Sender 重载 << 操作符,以实现将 Mail 类的数据发送出去,大致用法就是 Sender << Mail 这样的方式。这就涉及到了诸多问题。
1、运算符重载函数要写在哪个类中?
发送数据的格式为 Sender << Mail,很明显相当于 Sender.operator<<(Mail) 这样的操作,所以运算符重载函数要写到 Sender 类中。
2、Sender 要使用 Mail 类对象作为参数,需要访问 Mail 类中的私有成员怎么办?
此时友元就发挥了作用,我们需要将 Sender 类中的运算符重载函数在 Mail 类中声明为友元函数,这样 Sender 类才能正常访问 Mail 类的私有成员。这个问题类似我们之前介绍过的“类A的成员函数做类B的友元函数”。
具体实现的代码如下:
#include <iostream> #include <string> using namespace std; // 前向声明 Mail class Mail; class Sender { public: Sender(string addr) :_addr(addr){} // 操作符重载函数,返回 Sender 引用是为了连续的 << 操作 Sender& operator<<(Mail& mail); private: string _addr; }; class Mail { public: Mail(string title, string content) :_title(title), _content(content){} // 声明友元函数的时候要加域,否则他找不到是哪个 operator friend Sender& Sender::operator<<(Mail& mail); private: string _title; string _content; }; // Mail 类后面实现,防止访问不到类成员的情况 Sender& Sender::operator<<(Mail& mail) { cout << "To : " << _addr << endl; cout << "Title : " << mail._title << endl; cout << "Content : " << mail._content << endl; // 返回 *this 是为了连续 << 操作 return *this; } int main(int argc, char* argv[]) { Sender sender("3086417@qq.com"); Mail mail("节假日请你吃饭", "周末我们去外婆家吃老干妈吧。"); Mail mail2("你的QQ申诉邮件", "你的QQ申诉失败了!!"); sender << mail << mail2; return 0; }