【C++】实现复数类

用C++语言实现一个复数类,包括复数加、减、乘、除、加等、减等、乘等及除等8个运算符的重载。

#include <iostream>
using namespace std;
class Complex//复数类
{
	friend ostream& operator<<(ostream& _cout, const Complex& c);//重载<<操作符
public:
	Complex(const double real = 0.0, const double image = 0.0);//构造函数
	Complex(const Complex& c);//拷贝构造函数
	~Complex();//析构函数
	Complex& operator=(const Complex& c);//重载赋值运算符
	//对+,-,*,/及+=,-+,*=,/=运算符的重载
	Complex operator+(const Complex& c);
	Complex operator-(const Complex& c);
	Complex operator*(const Complex& c);
	Complex operator/(const Complex& c);
	Complex& operator+=(const Complex& c);
	Complex& operator-=(const Complex& c);
	Complex& operator*=(const Complex& c);
	Complex& operator/=(const Complex& c);
private:
	double _real;//复数实部
	double _image;//复数虚部
};
//类外实现成员函数
Complex::Complex(const double real, const double image)//构造函数
{
	_real = real;
	_image = image;
}
Complex::~Complex()//析构函数
{}
Complex::Complex(const Complex& c)//拷贝构造函数
{
	_real = c._real;
	_image = c._image;
}
Complex& Complex::operator=(const Complex& c)//重载赋值操作符
{
	if (this != &c)
	{
		_real = c._real;
		_image = c._image;
	}
	return *this;
}
Complex Complex::operator+(const Complex& c)//重载+
{
	Complex temp(_real + c._real, _image + c._image);
	return temp;
}
Complex Complex::operator-(const Complex& c)//重载-
{
	Complex temp(_real - c._real, _image - c._image);
	return temp;
}
Complex Complex::operator*(const Complex& c)//重载*
{
	Complex temp(_real*c._real - _image*c._image, _real*c._image + _image*c._real);
	return temp;
}
Complex Complex::operator/(const Complex& c)//重载/
{
	double ret = c._real*c._real + c._image*c._image;
	Complex temp((_real*c._real + _image*c._image) / ret, (_image*c._real - _real*c._image) / ret);
	return temp;
}
Complex& Complex::operator+=(const Complex& c)//重载+=
{
	_real += c._real;
	_image += c._image;
	return *this;
}
Complex& Complex::operator-=(const Complex& c)//重载-=
{
	_real -= c._real;
	_image -= c._image;
	return *this;
}
Complex& Complex::operator*=(const Complex& c)//重载*=
{
	_real = _real*c._real - _image*c._image;
	_image = _real*c._image + _image*c._real;
	return *this;
}
Complex& Complex::operator/=(const Complex& c)//重载/=
{
	double tmp = 0.0;
	double ret = c._real*c._real + c._image*c._image;
	tmp = (_real*c._real + _image*c._image) / ret;
	_image = (_image*c._real - _real*c._image) / ret;
	_real = tmp;
	return *this;
}
ostream& operator<<(ostream& _cout, const Complex& c)//重载<<操作符,使复数的打印形式为 a+bi
{
	_cout << c._real << "+" << c._image << "i";
	return _cout;
}

int main()
{
	//对部分功能的测试
	Complex a(1.0, 2.0);
	Complex b(3.0, 4.0);
	Complex c;
	Complex d(a);
	c = a / b;
	cout << c << endl;
	return 0;
}


  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值