设两个复数为
公式如下:
程序如下:
#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;
}
}
};
运行结果