Complex类是典型的不含指针的类。
下面贴出代码:
#ifndef __COMPLEX_H_
#define __COMPLEX_H_
// a += b += c; 结合律 right -> left
// cout << a << b; 结合律 left -> right
#include <iostream>
//编译器会生成默认的拷贝构造,拷贝赋值,和析构函数
class Complex {
public:
Complex(double re = 0, double im = 0) : real(re), imag(im) {}
Complex& operator+=(const Complex&);
Complex& operator-=(const Complex&);
Complex& operator*=(const Complex&);
Complex& operator/=(const Complex&);
double getImag() const{
return this->imag;
}
double getReal() const{
return this->real;
}
private:
double real;
double imag;
friend Complex& __doapl(Complex*, const Complex&);
friend Complex& __doami(Complex*, const Complex&);
friend Complex& __doaml(Complex*, const Complex&);
};
inline Complex&
__doapl(Complex* lhs, const Complex& rhs) {
lhs->real += rhs.real;
lhs->imag += rhs.imag;
return *lhs;
}
inline Complex&
Complex::operator+=(const Complex& rhs) {
return __doapl(this, rhs);
}
inline Complex&
__doami(Complex* lhs, const Complex& rhs) {
lhs->real -= rhs.real;
lhs->imag -= rhs.imag;
return *lhs;
}
inline Complex&
Complex::operator-=(const Complex& rhs) {
return __doami(this, rhs);
}
inline Complex&
__doaml(Complex* lhs, const Complex& rhs) {
double d = lhs->real * rhs.real - lhs->imag * rhs.imag;
lhs->imag = lhs->real * rhs.imag + lhs->imag * rhs.real;
lhs->real = d;
return *lhs;
}
inline Complex&
Complex::operator*=(const Complex& rhs) {
return __doaml(this, rhs);
}
std::ostream&
operator<<(std::ostream& os, const Complex& c) {
os << "(" << c.getReal() << "+" << c.getImag() << "i)" << std::endl;
return os;
}
#endif //__COMPLEX_H_
测试程序:
#include <iostream>
#include "Complex.h"
using namespace std;
int main(int argc, char** argv) {
Complex c1(2, 1);
Complex c2(4, 0);
cout << c1 << endl;
cout << c2 << endl;
c1 += c2;
cout << c1 << "\n";
return 0;
}
结果:
另一种含指针的类的实现,见这里。