任务
《电路理论》中相量法常需进行极坐标形式复数的运算,计算器上没有直接的计算方式,需要记录很多运算结果,往往很复杂。 C++备考时对运算符的重载掌握比较薄弱,一直没有练习的机会,因此决定实现极坐标形式复数类的计算。
已有
C++运行环境 复数运算规则
代码实现
/****Complex_p.h****/
#pragma once
#include
#include
#define PAI 3.1415926
using namespace std;
class Complex
{
public:
Complex(); //constructor without parameter
Complex(double); //constructor with one parameter
Complex(double,double); //constructor with two parameters
inline void operator =(const Complex& c)//重载双目运算符赋值
{
r = c.r;
a = c.a;
}
inline void operator +=(Complex c)//重载双目运算符加赋值
{
*this = *this + c;
}
inline void operator -=(Complex c)//重载双目运算符减赋值
{
*this = *this - c;
}
Complex operator -()const;//重载单目运算符减
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 istream& operator>>(istream& is, Complex& c);//输入
friend ostream& operator
r = x0;
a = x0;
}
Complex::Complex(double r0, double a0)
{
r = r0;
a = a0;
}
Complex operator+(Complex& c1, Complex& c2)
{
Complex temp;
double re, im;
re = c1.r * cos(A2R(c1.a)) + c2.r * cos(A2R(c2.a));
im = c1.r * sin(A2R(c1.a)) + c2.r * sin(A2R(c2.a));
temp.r = sqrt(re * re + im * im);
temp.a = R2A(atan(im / re));
return temp;
}
Complex Complex::operator -()const
{
Complex temp;
temp.r = r;
temp.a = a + 180;
return temp;
}
Complex operator-(Complex& c1, Complex& c2)
{
Complex temp;
double re, im;
re = c1.r * cos(A2R(c1.a)) - c2.r * cos(A2R(c2.a));
im = c1.r * sin(A2R(c1.a)) - c2.r * sin(A2R(c2.a));
temp.r = sqrt(re * re + im * im);
temp.a = R2A(atan(im / re));
return temp;
}
Complex operator/(Complex& c1, Complex& c2)
{
return Complex(c1.r / c2.r, c1.a - c2.a);
}
Complex operator*(Complex& c1, Complex& c2)
{
return Complex(c1.r * c2.r, c1.a + c2.a);
}
istream& operator>>(istream& is, Complex& c)
{
cout c.r;
cout c.a;
return is;
}
ostream& operator
if (r
a -= 360;
}
return Complex(r, a);
}
void Complex:: display()
{
cout
return a * 180 / PAI;
}
/****main.cpp****/
#include
using namespace std;
#include"Complex_p.h"
int main(void)
{
Complex c1, c2,c;
getOperands(c1, c2);
char choice;
tips();
cin >> choice;
while (choice!='q')
{
switch (choice)
{
case'a':
c = c1 + c2;
cout |