声明一个复数类 Complex,重载运算符”+”,“-”,“*”,“/”,使之能用于复数的加、减、乘、除,运算符重载函数作为 Complex类的成员函数。编程序,分别求两个复数之和、差、积和商。
1.程序代码:
#include<iostream>
using namespace std;
class complex
{
public:
complex() { real = 0; imag = 0; } //定义构造函数
complex(double r, double i) { real = r; imag = i; } //构造函数重载
complex operator+(complex& c2); //声明运算符重载成员函数
complex operator-(complex& c2);
complex operator*(complex& c2);
complex operator/(complex& c2);
void display();
private:
double real;
double imag;
};
///重载运算符+
complex complex::operator+(complex& c2)
{
complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
///重载运算符-
complex complex::operator-(complex& c2)
{
complex c;
c.real = real - c2.real;
c.imag = imag - c2.imag;
return c;
}
//重载运算符*
complex complex::operator*(complex& c2)
{
complex c;
c.real = real * c2.real;
c.imag = imag * c2.imag;
return c;
}
//重载运算符/
complex complex::operator/(complex& c2)
{
complex c;
c.real = real / c2.real;
c.imag = imag / c2.imag;
return c;
}
void complex::display()
{
cout << "(" << real << "," << imag << ")" << endl;
}
int main()
{
complex c1(3,5), c2(3,-10),c3;
cout << endl;
cout << "c1="; c1.display();
cout << "c2="; c2.display();
cout << endl;
c3 = c1 + c2;
cout << "c1+c2="; c3.display();
cout << endl;
c3 = c1 - c2;
cout << "c1-c2="; c3.display();
cout << endl;
c3 = c1 * c2;
cout << "c1*c2="; c3.display();
cout << endl;
c3 = c1 / c2;
cout << "c1/c2="; c3.display();
return 0;
}
2.运行结果: