Oracle Solaris Studio 12.2:C++ 用户指南

13.3.1.1 定义自己的插入运算符

以下示例定义了 string 类:


#include <stdlib.h>
#include <iostream.h>


class string {
private:
    char* data;
    size_t size;

public:
    // (functions not relevant here)

    friend ostream& operator<<(ostream&, const string&);
    friend istream& operator>>(istream&, string&);
};

在此示例中,必须将插入运算符和提取运算符定义为友元,因为 string 类的数据部分是 private


ostream& operator<< (ostream& ostr, const string& output)
{    return ostr << output.data;}

以下是为要用于 string 而重载的 operator<< 的定义。


cout << string1 << string2;

运算符 <<ostream&(也就是对 ostream 的引用)作为其第一个参数,并返回相同的 ostream,这样就可以在一个语句中合并多个插入。