#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;
}
C++ 复数类
最新推荐文章于 2022-04-17 10:55:22 发布