C++ 复数类

#include<iostream>
#include<math.h>
using namespace std;
class Complex
{
private:
	double real;
	double image;
public:
	Complex()
	{
		real = 0;
		image = 0;
	}
	Complex(double r, double i)
	{
		real = r;
		image = i;
	}
	Complex(int r)
	{
		real = r;
		image = 0;
	}
	double abs()//求复数信息的绝对值
	{
		double d = sqrt(pow(real, 2) + pow(image, 2));
		return d;
	}
	void display()//复数信息的输出
	{
		cout << "(" << real << "," << image << ")" << endl;
	}
	Complex operator++(); //"++" 重载为成员函数
	Complex operator--(); //"--" 重载为成员函数
	friend Complex operator+(Complex& c1, Complex& c2);//声明为友元函数,可以访问该类的私有成员
	friend Complex operator-(Complex& c1, Complex& c2);//声明为友元函数,可以访问该类的私有成员
	friend Complex operator*(Complex& c1, Complex& c2);//声明为友元函数,可以访问该类的私有成员
	friend Complex operator/(Complex& c1, Complex& c2);//声明为友元函数,可以访问该类的私有成员
	friend Complex operator^(Complex c1, int n);//声明为友元函数,可以访问该类的私有成员
};

Complex operator+(Complex& c1, Complex& c2)//复数的加法
{
	return Complex(c1.real + c2.real, c1.image + c2.image);
}
Complex operator-(Complex& c1, Complex& c2)//复数的减法
{
	return Complex(c1.real - c2.real, c1.image - c2.image);
}
Complex operator*(Complex& c1, Complex& c2)//复数的乘法
{
	double r = c1.real * c2.real - c1.image * c2.image;
	double i = c1.real * c2.image + c1.image * c2.real;
	return Complex(r, i);
}
Complex operator/(Complex& c1, Complex& c2)//复数的除法
{
	double r = (c1.real * c2.real + c1.image * c2.image) / (pow(c2.real, 2) + pow(c2.image, 2));
	double i = (c2.real * c1.image - c1.real * c2.image) / (pow(c2.real, 2) + pow(c2.image, 2));
	return Complex(r, i);
}

Complex operator^(Complex c1, int n)//复数的乘方
{    
	double abs_c1 = sqrt(c1.real * c1.real + c1.image * c1.image);
	double theta = atan(c1.image / c1.real);
	theta = theta * n;
	abs_c1 = pow(abs_c1, n);
	return Complex(abs_c1 * cos(theta), abs_c1 * sin(theta));
}

Complex Complex::operator++()//复数的自加
{
	this->real += 1;
	this->image += 1;
	return *this;
}
Complex Complex::operator--()//复数的自减
{
	this->real -= 1;
	this->image -= 1;
	return *this;
}

int main()
{
	Complex a(5, 8), b(2, 2), c(0, 0);
	++a;
	--b;
	a.display();//a(6,9)
	b.display();//b(1,1)
	c = a + b;
	c.display();
	c = a - b;
	c.display();
	c = a * b;
	c.display();
	c = a / b;
	c.display();
	c = a ^ 2;
	c.display();
	cout << c.abs() << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值