格式

第一操作数是标准类类型ostream的对象的引用,比如:“&out”,第二操作数是本类的对象

  1. ostream &operator<<(ostream &out, const 类类型 &obj );//重载<<

示例

  1. #pragma once
  2. #include<algorithm>
  3. #include<functional>
  4. #include<iostream>
  5. using namespace std;
  6. class Complex {
  7. private:
  8. double real;
  9. double imag;
  10. public:
  11. Complex(double real, double imag) :real(real), imag(imag) {}
  12. Complex() :real(0), imag(0) {}
  13. Complex(const Complex& c) :real(c.real), imag(c.imag) {}
  14. Complex& operator=(const Complex& c) {
  15. real = c.real;
  16. imag = c.imag;
  17. return *this;
  18. }
  19. Complex operator+(const Complex& c)const {
  20. return Complex(real + c.real, imag + c.imag);
  21. }
  22. Complex operator-(const Complex& c) {
  23. return Complex(real - c.real, imag - c.imag);
  24. }
  25. Complex operator*(const Complex& c) {
  26. return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
  27. }
  28. Complex operator/(const Complex& c) {
  29. return Complex((real * c.real + imag * c.imag) / (c.real * c.real + c.imag * c.imag), (imag * c.real - real * c.imag) / (c.real * c.real + c.imag * c.imag));
  30. }
  31. double getReal() {
  32. return real;
  33. }
  34. double getImag() {
  35. return imag;
  36. }
  37. friend ostream& operator<<(ostream& os, const Complex& c);
  38. };
  39. ostream& operator<<(ostream& os, const Complex& c) {
  40. os << c.real << " + " << c.imag << "i";
  41. return os;
  42. }

调用

因为plus()中的参数是常量对象,因此只能调用常量成员函数,因此重载加法运算符要用const修饰

  1. #include"Complex.h"
  2. Complex operator+(Complex& c1, Complex& c2) {
  3. return Complex(c1.getReal() + c2.getReal(), c1.getImag() + c2.getImag());
  4. }
  5. void testComplex() {
  6. Complex c1(1, 2);
  7. Complex c2(3, 4);
  8. Complex c3 = c1 + c2;
  9. cout << c3 << endl;
  10. plus<Complex> c4;
  11. cout << c4(c1, c2)<< endl;
  12. cout << c1 - c2 << endl;
  13. }
  14. int main() {
  15. testComplex();
  16. }

运行结果

image.png