运算符重载 的正规写法一般都是 使用 成员函数 的形式 实现的 ;
上述 运算符重载 既可以使用 成员函数 进行重载 , 又可以使用友元函数进行重载 ;
只能使用 成员函数 重载的运算符 : = , [] , () , -> 等操作符 只能使用 成员函数 进行重载 ;
只能使用 友元函数 重载的运算符 : 无法修改 左操作数 的情况下 , 只能使用 全局函数 ( 需声明 友元函数 ) 进行重载 ;
平时使用 cout 与 左移操作符 << 向命令行输出数据时 , 只能输出 基础数据类型 和 字符串 ;
cout << "age = " << age << endl;
如果 , 想要输出 自定义类对象 , 直接使用下面的代码 , 会报错 ;
// 自定义类型相加
Student s1(10, 120), s2(18, 170);
// 输出对象
cout << s1 << endl;
编译时 , 会提示 如下错误 :
error C2679: 二进制“<<”: 没有找到接受“Student”类型的右操作数的运算符(或没有可接受的转换)

如果想要使用 cout << s1 << endl; 用法输出对象到日志中 , 需要重载 左移操作符 ;
使用 全局函数 实现 左移运算符 << 重载 :
cout << s1 左移操作符重载 , 函数名规则为 " operate " 后面跟上要重载的运算符 , 函数名是 operate<< ;operate<<
cout << s1 左操作数是 ostream cout 标准输出流 , 参数中是引用类型 ;cout << s1 右操作数是 Student s 类对象 , 参数中是引用类型 ;operator<<(ostream& out, Student& s)
ostream& operator<<(ostream& out, Student& s)
// 全局函数 中实现 Student 左移运算符重载
// 返回 ostream& 引用类型 , 是为了支持链式调用 cout << s1 << endl;
ostream& operator<<(ostream& out, Student& s)
{
// 在函数体中将 Student 对象数据输出到 out 输出流中
out << s.age << " , " << s.height << endl;
// 该返回值还需要当左值使用
return out;
}
代码示例 :
#include "iostream"
using namespace std;
class Student
{
public:
// 带参构造函数 , 为参数设置默认值
Student(int age = 1, int height = 1)
{
this->age = age;
this->height = height;
};
public:
// 打印类数据
void print()
{
cout << "age = " << age << " , height = " << height << endl;
};
public:
int age; // 年龄
int height; // 身高
};
// 全局函数 中实现 Student 左移运算符重载
// 返回 ostream& 引用类型 , 是为了支持链式调用 cout << s1 << endl;
ostream& operator<<(ostream& out, Student& s)
{
// 在函数体中将 Student 对象数据输出到 out 输出流中
out << s.age << " , " << s.height << endl;
// 该返回值还需要当左值使用
return out;
}
int main() {
// 自定义类型相加
Student s1(10, 120), s2(18, 170);
// 输出对象 , 此时 函数执行返回值 当左值
cout << s1;
// cout << s1 返回了 ostream& 类型引用
// 然后执行 ostream cout << endl
cout << s1 << endl;
// 控制台暂停 , 按任意键继续向后执行
system("pause");
return 0;
};
执行结果 :
10 , 120
10 , 120
请按任意键继续. . .
