定义一个复数类,重载运算符“+”、“-”、“*”、“、”,使之能用于复数的加、减、乘、除。要求:重载运算符“+”、“-”用成员函数;重载运算符“*”、“/”用友元函数,实现两个复数的和、差、积、商。
代码如下:
头文件()代码如下:
#pragma once
class complex {
private:
double real;//实部
double image;//虚部
public:
complex();//不带参构造函数
complex(double r, double i);//带参构造函数。
void show();//打印输出
complex operator+(complex& a);//用成员函数,重载运算符“+”
complex operator-(complex& a); //用成员函数,重载运算符“ - ”
//用友元函数,重载运算符“ * ”
friend complex operator*(complex& a,complex &b);
//用友元函数,重载运算符“ / ”
friend complex operator/(complex& a, complex& b);
~complex();
};
main代码如下:
#include<iostream>
using namespace std;
#include"anew.h"
complex::complex() {
real = 0;
image = 0;
}
complex::complex(double r, double i) {
real = r;
image = i;
}
complex complex::operator+(complex& a) {
complex temp;
temp.real = real + a.real;
temp.image = image + a.image;
return temp;
}
complex complex::operator-(complex& a) {
complex temp;
temp.real = real - a.real;
temp.image = image - a.image;
return temp;
}
complex operator*(complex& a, complex& b) {
complex temp;
temp.real = a.real * b.real - a.image * b.image;
temp.image = a.image * b.real + a.real * b.image;
return temp;
}
complex operator/(complex& a, complex& b) {
complex temp;
temp.real = (a.real * b.real +a.image * b.image)/(b.real*b.real+b.image*b.image);
temp.image=(a.image*b.real-a.real*b.image)/(b.real * b.real + b.image * b.image);
return temp;
}
void complex::show() {
cout << "(" << real << "," << image << "i"<<")" << endl;
}
void main()
{
complex a1(1,2),a2(3,4);
cout << "两个复数为:"<<endl;
cout <<"a1=";
a1.show();
cout << "a2=";
a2.show();
complex sum,sub,mul,div;
cout << "两个复数相加为:" << endl;
sum = a1 + a2;
cout << "a1+a2=";
sum.show();
cout << "两个复数相减为:" << endl;
sub = a1 - a2;
cout << "a1-a2=";
sub.show();
cout << "两个复数相乘为:" << endl;
mul = a1 * a2;
cout << "a1*a2=";
mul.show();
cout << "两个复数相除为:" << endl;
div = a1 / a2;
cout << "a1/a2=";
div.show();
}
运行截图如下:
代码仅供参考