格式
第一操作数是标准类类型ostream的对象的引用,比如:“&out”,第二操作数是本类的对象
ostream &operator<<(ostream &out, const 类类型 &obj );//重载<<
示例
#pragma once
#include<algorithm>
#include<functional>
#include<iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double real, double imag) :real(real), imag(imag) {}
Complex() :real(0), imag(0) {}
Complex(const Complex& c) :real(c.real), imag(c.imag) {}
Complex& operator=(const Complex& c) {
real = c.real;
imag = c.imag;
return *this;
}
Complex operator+(const Complex& c)const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) {
return Complex(real - c.real, imag - c.imag);
}
Complex operator*(const Complex& c) {
return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real);
}
Complex operator/(const Complex& c) {
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));
}
double getReal() {
return real;
}
double getImag() {
return imag;
}
friend ostream& operator<<(ostream& os, const Complex& c);
};
ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
调用
因为plus
#include"Complex.h"
Complex operator+(Complex& c1, Complex& c2) {
return Complex(c1.getReal() + c2.getReal(), c1.getImag() + c2.getImag());
}
void testComplex() {
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2;
cout << c3 << endl;
plus<Complex> c4;
cout << c4(c1, c2)<< endl;
cout << c1 - c2 << endl;
}
int main() {
testComplex();
}