一个很简单的关于运算符重载的小的样例。
#include<iostream>
using namespace std;
class Complex {
public:
friend ostream &operator<<(ostream &, Complex &);
friend istream &operator>>(istream &, Complex &);
private:
double real;
double imag;
};
//istream和ostream类对象的引用,两个参数也是类对象的引用
//operator<<可以理解为重载函数名,编译系统将之解释为operator<<(cout,c3)
ostream &operator<<(ostream &output, Complex &c) {
output << "(" << c.real ;
if(c.imag>=0){
output<<"+";
}
output<<c.imag<<"i)"<<endl;
return output;
}
//形参input和output就是cin和cout的别名
istream &operator>>(istream &input, Complex &c) {
cout << "input real part and imaginary part of complex number:";
input >> c.real >> c.imag;
return input;
}
int main() {
Complex c1, c2;
cin >> c1 >> c2;
cout << "c1=" << c1 << endl;
cout << "c2=" << c2 << endl;
}