博客第一篇文章
数据结构复数
/*
1.什么是抽象数据类型?试用C++的类声明定义“复数”的抽象数据类型。要求
(1) 在复数内部用浮点数定义它的实部和虚部。
(2) 实现3个构造函数:缺省的构造函数没有参数;第二个构造函数将双精度浮点数赋给复数的实部,虚部置为0;第三个构造函数将两个双精度浮点数分别赋给复数的实部和虚部。
(3) 定义获取和修改复数的实部和虚部,以及+、-、*、/等运算的成员函数。
(4) 定义重载的流函数来输出一个复数
*/
/*
1.什么是抽象数据类型?试用C++的类声明定义“复数”的抽象数据类型。要求
(1) 在复数内部用浮点数定义它的实部和虚部。
(2) 实现3个构造函数:缺省的构造函数没有参数;第二个构造函数将双精度浮点数赋给复数的实部,虚部置为0;第三个构造函数将两个双精度浮点数分别赋给复数的实部和虚部。
(3) 定义获取和修改复数的实部和虚部,以及+、-、*、/等运算的成员函数。
(4) 定义重载的流函数来输出一个复数
*/
#include<iostream>
using namespace std;
class plural
{
public:
plural();
plural(double);
plural(double,double);
void setReal(double);
void setImaginary(double);
double getReal()const;
double getImaginary()const;
plural &operator =(const plural &pl);
~plural();
private:
double real;
double imaginary;
};
plural::plural()
{
real = 0;
imaginary = 0;
}
plural::plural(double r)
{
real = r;
imaginary = 0;
}
plural::plural(double r,double i)
{
real = r;
imaginary = i;
}
plural::~plural()
{
}
void plural::setReal(double r)
{
real = r;
}
void plural::setImaginary(double i)
{
imaginary = i;
}
double plural::getReal()const
{
return real;
}
double plural::getImaginary()const
{
return imaginary;
}
bool operator == (const plural &pl1,const plural &pl2)
{
return pl1.getImaginary() == pl2.getImaginary() && pl1.getImaginary() == pl2.getImaginary();
}
plural operator +(const plural &pl1, const plural &pl2)
{
plural temp(pl1.getReal()+pl2.getReal(),pl1.getImaginary()+pl2.getImaginary());
return temp;
}
plural &plural:: operator =(const plural &pl)
{
this->setReal(pl.getReal());
this->setImaginary(pl.getImaginary());
return *this;
}
plural operator -(const plural &pl1, const plural &pl2)
{
plural temp(pl1.getReal() - pl2.getReal(), pl1.getImaginary() - pl2.getImaginary());
return temp;
}
plural operator *(const plural &pl1, const plural &pl2)
{
double tempR= pl1.getReal()*pl2.getReal() - pl1.getImaginary()*pl2.getImaginary();
double tempI=pl1.getImaginary()*pl2.getReal() + pl2.getImaginary()*pl1.getReal();
plural temp(tempR,tempI);
return temp;
}
plural operator /(const plural &pl1, const plural &pl2)
{
plural temp1(pl2.getReal(), -pl2.getImaginary());
plural temp2 = pl1*temp1 / (pl2.getReal()*pl2.getReal() + pl2.getImaginary()*pl2.getImaginary());
return temp2;
}
ostream &operator<<(ostream &os,const plural &pl)
{
char temp;
os << pl.getReal();
if (pl.getImaginary()==0) return os;
else if (pl.getImaginary() > 0)temp = '+';
else temp = '-';
os << temp << pl.getImaginary() <<' i';
return os;
}
int main()
{
plural temp(1, 1);
plural temp2(1, -1);
cout << temp << endl << temp*temp2 << endl<< temp + temp2 << endl << temp - temp2 << endl << temp / temp2;
system("pause");
}