C++ Complex类 重载运算符 + - * /

设两个复数为 a = x_1 + y_1i, b = x_2 + y_2i

公式如下:

a + b = (x_1 + x_2) + (y_1 + y_2)i

a - b = (x_1 - x_2) + (y_1 - y_2)i;

a * b = (x_1 + y_1i) * (x_2 + y_2i) = (x_1*x_2 - y_1*y_2) + (x_1 * y_2 - y_1 * x_2)i;

a / b = (x_1 + y_1i) / (x_2 + y_2i) = (x_1 * x_2 + y_1 * y_2) / (x_2 * x_2 + y_2 * y_2) + [(x_2 * y_1 - x_1 * y_2) / (x_2 * x_2 + y_2 * y_2)]i;

程序如下:

#include <iostream>

using namespace std;

class Complex {
public:
	double real, imag;
	Complex():real(0),imag(0) {}//无参构造函数
	Complex(double r, double i):real(r),imag(i){}// 用参数初始化表对其数据成员初始化
	void display();
};

//重载运算符+ (重载为普通函数)
Complex operator+ (const Complex& a, const Complex& b)
{
	return Complex(a.real + b.real, a.imag + b.imag); //返回一个临时对象
}

//重载运算符- (重载为普通函数)
Complex operator- (const Complex& a, const Complex& b)
{
	return Complex(a.real - b.real, a.imag - b.imag); 	//返回一个临时对象
}

//重载运算符* (重载为普通函数)
Complex operator*(const Complex& a, const Complex& b)
{
	Complex c;
	c.real = a.real * b.real - a.imag * b.imag;
	c.imag = a.real * b.imag + a.imag * b.real;
	return c;
}

//重载运算符/ (重载为普通函数)
Complex operator/(const Complex& a, const Complex& b)
{
	Complex c;
	c.real = (a.real * b.real + a.imag * b.imag) / (b.real * b.real + b.imag * b.imag);
	c.imag = (b.real * a.imag - a.real * b.imag) / (b.real * b.real + b.imag * b.imag);
	return c;
}

void Complex::display()
{
	if (imag < 0) {
		cout << real << " - " << -imag << "i" << endl;
	}
	else {
		cout << real << " + " << imag << "i" << endl;
	}
}

int main()
{
	Complex a(3, 4), b(5, -10), c1, c2, c3, c4;

	c1 = a + b;
	c2 = a - b;
	c3 = a * b;
	c4 = a / b;

	cout << "c1 = a + b = ";c1.display();

	cout << "c2 = a - b = "; c2.display();

	cout << "c3 = a * b = "; c3.display();

	cout << "c4 = a / b = "; c4.display();

	return 0;
}

 重载为成员函数

class Complex {
public:
	double real, imag;
	Complex():real(0),imag(0) {}//无参构造函数
	Complex(double r, double i):real(r),imag(i){}//用参数初始化表对其数据成员初始化
	Complex operator+(const Complex& a){
		return Complex(real + a.real, imag + a.imag);
	}
	Complex operator-(const Complex& a) {
		return Complex(real - a.real, imag - a.imag);
	}
	Complex operator*(const Complex& a) {
		return Complex(real * a.real - imag * a.imag, real * a.imag + imag * a.real);
	}
	Complex operator/(const Complex& a) {
		Complex c;
		c.real = (real * a.real + imag * a.imag) / (a.real * a.real + a.imag * a.imag);
		c.imag = (a.real * imag - real * a.imag) / (a.real * a.real + a.imag * a.imag);
		return c;
	}
	void display() {
		if (imag < 0) {
			cout << real << " - " << -imag << "i" << endl;
		}
		else {
			cout << real << " + " << imag << "i" << endl;
		}
	}
};

 运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值