C++ Complex + - += -+ <<运算符重载
Posted yangshengjing
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ Complex + - += -+ <<运算符重载相关的知识,希望对你有一定的参考价值。
/*
提供了加减运算符重载的复数类头文件。关于传递引用和传递值,使用const 和不使用const,关于指针成员的使用需要继续学习。。。
同理可以写出乘除法,共轭复数,绝对值, 等其他运算符重载。
*/
#ifndef _COMPLEX_H_
#define _COMPLEX_H_
#include<iostream>
using namespace std;
class Complex
public:
//构造函数
Complex(double r = 0, double i = 0):re(r), im(i) //在函数体内是赋值assignment re=r im=i
//拷贝构造函数
Complex(const Complex &temp);
//返回实部
double real()constreturn re;
//返回虚部
double imag()constreturn im;
//重载各种运算符
Complex &operator+=(const Complex &);
// ostream &operator<<(ostream &); temp<<cout 形式 为顺应使用习惯 必须写成非成员函数。
Complex &operator = (const Complex &);
Complex &operator-=(const Complex &);
private:
double re;
double im;
//friend Complex &_doapl(Complex *, const Complex &r);
;
//拷贝构造函数
inline Complex::Complex(const Complex &temp):re(temp.real()),im(temp.imag())
//重载= 就是赋值
inline Complex &Complex::operator = (const Complex &temp)
re = temp.real();
im = temp.imag();
return *this;
//重载+=
inline Complex &Complex::operator += (const Complex &temp)
this->re = this->re + temp.real();
this->im = this->im + temp.imag();
return *this;
//重载-=
inline Complex &Complex::operator -= (const Complex &temp)
this->re = this->re - temp.real();
this->im = this->im - temp.imag();
return *this;
//重载<<
inline ostream &operator << (ostream &os, const Complex &temp)
if (temp.imag() == 0)
if (temp.real())
return os << temp.real();
return os << 0;
else if (temp.imag() > 0)
if (temp.real())
return os << temp.real() << "+" << temp.imag() << "i";
return os << temp.imag() << "i";
else
if (temp.real())
return os << temp.real() << temp.imag() << "i";
return os << temp.imag() << "i";
//重载 Complex+double
inline Complex operator +(const Complex &x, double &y)
return Complex(x.real() + y, x.imag());
//重载 Complex+Complex
inline Complex operator +(const Complex &x, const Complex &y)
return Complex(x.real() + y.real(), x.imag() + y.imag());
//重载 double+Complex
inline Complex operator +(double &y, const Complex &x)
return Complex(x.real() + y, x.imag());
//重载+Complex
inline Complex operator +(const Complex &x)
return x;
//重载 Complex-double
inline Complex operator -(const Complex &x, double &y)
return Complex(x.real() - y, x.imag());
//重载 Complex-Complex
inline Complex operator -(const Complex &x, const Complex &y)
return Complex(x.real() - y.real(), x.imag() - y.imag());
//重载 double-Complex
inline Complex operator -(double &y, const Complex &x)
return Complex(y-x.real(), -x.imag());
//重载-Complex
inline Complex operator -(const Complex &x)
return Complex(-x.real(), -x.imag());
#endif // !_COMPLEX_H_
//如果有错误,或者低能的地方,欢迎指出,感激不尽!!!!!1
以上是关于C++ Complex + - += -+ <<运算符重载的主要内容,如果未能解决你的问题,请参考以下文章