本文主要是介绍C++ 复数类的定义,包含初始化,求绝对值,输出,复数的加、减、乘、除、乘方、自加、自减等。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
要求:
- 复数类
- 复数信息的初始化
- 复数信息的输出
- 求复数的绝对值
- 实现复数的加、减、乘、除、乘方、自加、自减等。
代码:
#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--(int); //"--" 重载为成员函数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--(int)//复数的自减
{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++ 复数类的定义,包含初始化,求绝对值,输出,复数的加、减、乘、除、乘方、自加、自减等。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!