#ifndef __Complex__
#define __Complex__
#include<iostream>
using namespace std;
//using std::cout;
//using std::ostream;
/*前向声明*/
//class ostream;
class Complex;
Complex& _doapl(Complex* ths, const Complex& r);
/*类声明*/
class Complex {
public:
Complex(double a=0,double b=0):re(a),im(b){}
double real() const { return re; }
double imag() const { return im; }
Complex& operator+=(const Complex& r);
//Complex& _doapl(Complex* ths, const Complex& r);
private:
double re, im;
friend Complex& _doapl(Complex* ths, const Complex& r);
};
/*类定义*/
//这个应该就是class类内互为友元
//inline Complex& Complex::_doapl(Complex* ths, const Complex& r) {
// ths->re += r.re;
// ths->im += r.im;
// return *ths;
//}
//此函数如果不是友元函数就不能访问复数类中的私有成员变量
inline Complex& _doapl(Complex* ths, const Complex& r) {
ths->re += r.re;
ths->im += r.im;
return *ths;
}
//+=运算符考虑重载运算符的时候返回值应该为complex&,而不能是void
//不然当有多个连续的 += 运算时会报错,因为返回值为void,不能再进行 += 运算
inline Complex& Complex::operator+=(const Complex& r) {
return _doapl(this, r);
}
/*非成员函数的定义*/
inline double imag(const Complex& x) {
return x.imag();
}
inline double real(const Complex& x) {
return x.real();
}
//为了对付client的三种可能用法,开发三个函数(非成员函数)
//因为返回值为临时对象所以返回值不能是引用
inline Complex operator+(const Complex& x, const Complex& y) {
return Complex(real(x) + real(y), imag(x) + imag(y));
}
inline Complex operator+(const Complex& x, double y) {
return Complex(real(x) + y, imag(x));
}
inline Complex operator+(double x, const Complex& y) {
return Complex(x + real(y), imag(y));
}
//反相取反
inline Complex operator+(const Complex& x) {
return x;
}
//绝不可以return by reference,因为其返回的必定是个local object
inline Complex operator-(const Complex& x) {
return Complex(-real(x), -imag(x));
}
inline bool operator==(const Complex &x, const Complex& y) {
return real(x) == real(y) && imag(x) == imag(y);
}
inline bool operator==(const Complex &x, double y) {
return real(x) == y && imag(x) == 0;
}
inline bool operator==(double x, const Complex& y) {
return x == real(y) && 0 == imag(y);
}
inline bool operator!=(const Complex &x, const Complex& y) {
return real(x) != real(y) || imag(x) != imag(y);
}
inline bool operator!=(const Complex &x, double y) {
return real(x) != y || imag(x) != 0;
}
inline bool operator!=(double x, const Complex& y) {
return x != real(y) || 0 != imag(y);
}
inline Complex conj(const Complex& x) {
return Complex(real(x), -imag(x));
}
ostream& operator<<(ostream& os, const Complex& c) {
return os << '(' << real(c) << ',' << imag(c)<<')';
}
int main() {
Complex c1(2, 1);
Complex c2(5);
c2 += c1;
c2 += c2 += c1;//+=重载返回值不能是void
//client的三种可能用法
c2 = c1 + c2;
c2 = c1 + 5;
c2 = 7 + c1;
// cout << c2 << endl;
cout << -c1 << endl;
cout << +c1 << endl;
cout << (c1 == c2);
cout << (c1 == 2);
cout << (0 == c2);
}
#endif
C++ Complex类(without pointer member(s))
最新推荐文章于 2024-01-16 17:04:52 发布