complex.h
#include <iostream.h>//using namespace std;
class complex {
private:
float real;
float imag;
public:
complex(float r = 0, float i = 0);
void print();
friend complex operator + (const complex &a, const complex &b);
friend complex operator ++(complex &a);
};
complex.cpp
#include "complex.h"
complex::complex(float r, float i) {
real = r;
imag = i;
}
void complex::print() {
cout << real;
if (imag != 0)
{
if (imag>0)
cout << "+" << imag << "i";
else
cout << "-" << imag << "i";
}
cout << endl;
}
complex operator +(const complex &a, const complex &b) {
complex exam;
exam.real = a.real + b.real;
exam.imag = a.imag + b.imag;
return exam;
//return *this;
}
complex operator ++(complex &a)
{
// a.real=a.real+1;
// a.imag=a.imag+1;
++a.real;
++a.imag;
return a;
}
main.cpp
#include "1.h"
int main(){
complex c1(1.5, 2.5), c2(2, 3), c3;
cout << "原始的c1是:";
c1.print();
cout << "原始的c2是:";
c2.print();
c3 = operator+(c1, c2);
// c3=c2+c1;
cout << "c3=c2+c1 is: ";
c3.print();
operator ++(c2);
cout << "after added 1 ,c2 is:";
c2.print();
return 0;
}
转载自书本《面向对象程序设计几C++》