operator <运算符>
例1 :复数的+、-、=运算
// 文件1:complex1.h--复数类的定义
#ifndef COMPLEX1_H
#define COMPLEX1_H
class Complex {
public:
Complex(double = 0.0, double = 0.0);
Complex operator+(const Complex&) const;
Complex operator-(const Complex&) const;
Complex& operator=(const Complex&);
void print() const;
private:
double real; // real part
double imaginary; // imaginary part
};
#endif
//文件2:complex1.cpp--复数类的成员函数定义
#include <iostream.h>
#include "complex1.h"
Complex::Complex(double r, double i)
{ real = r;
imaginary = i;
}
Complex Complex::operator+(const Complex &operand2) const
{
Complex sum;
sum.real = real + operand2.real;
sum.imaginary=imaginary + operand2.imaginary;
return sum;
}
Complex Complex::operator-(const Complex &operand2) const
{
Complex diff;
diff.real = real - operand2.real;
diff.imaginary=imaginary - operand2.imaginary;
return diff;
}
Complex& Complex::operator=(const Complex &right)
{
real = right.real;
imaginary = right.imaginary;
return *this; // enables concatenation
}
void Complex::print() const
{ cout<<'('<<real<< ", " << imaginary << ')'; }
//文件3: FIG13_1.cpp--主函数定义
#include <iostream.h>
#include "complex1.h"
main()
{
Complex x, y(4.3, 8.2), z(3.3, 1.1);
cout << "x: ";
x.print();
cout << "\ny: ";
y.print();
cout << "\nz: ";
z.print();
x = y + z;
cout << "\n\nx = y + z:\n";
x.print();
cout << " = ";
y.print();
cout << " + ";
z.print();
x = y - z;
cout << "\n\nx = y - z:\n";
x.print();
cout << " = ";
y.print();
cout << " - ";
z.print();
cout << '\n';
return 0;
}
程序执行结果:
x: (0, 0)
y: (4.3, 8.2)
z: (3.3, 1.1)
x = y + z:
(7.6, 9.3) = (4.3, 8.2) + (3.3, 1.1)
x = y - z:
(1, 7.1) = (4.3, 8.2) - (3.3, 1.1)