设计一个复数类,实现复数的加、减操作.(考查知识点:类的定义和实现.)用C++进行
来源:学生作业帮助网 编辑:六六作业网 时间:2024/11/23 04:42:31
设计一个复数类,实现复数的加、减操作.(考查知识点:类的定义和实现.)用C++进行
设计一个复数类,实现复数的加、减操作.(考查知识点:类的定义和实现.)
用C++进行
设计一个复数类,实现复数的加、减操作.(考查知识点:类的定义和实现.)用C++进行
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double fReal = 0.0, double fImag = 0.0):
m_fReal(fReal),m_fImag(fImag){}
public:
double GetReal(void) const {return m_fReal;}
double GetImag(void) const {return m_fImag;}
public:
void SetReal(double fReal)
{
m_fReal = fReal;
}
void SetImag(double fImag)
{
m_fImag = fImag;
}
public:
void Print(void)
{
cout << "[ " << m_fReal << " + " << m_fImag <<"i ]" << endl;
}
/////////////////////////////////////////////////////////////////////
public:
// 重载运算符前++,实部,虚部各加1
Complex& operator++ (void)
{
++m_fReal;
++m_fImag;
return *this;
}
// 重载运算符后++,实部,虚部各加1
// 加const修饰,使得编译时就报错,避免对后++的连续使用
const Complex operator++ (int)
{
Complex old = *this;
m_fReal++;
m_fImag++;
return old;
}
public:
Complex operator- (void)
{
return Complex(-m_fReal,-m_fImag);
}
public:
Complex operator+ (const Complex &c)
{
return Complex(m_fReal+c.m_fReal,m_fImag+c.m_fImag);
}
Complex operator- (const Complex &c)
{
return Complex(m_fReal-c.m_fReal,m_fImag-c.m_fImag);
}
Complex& operator+= (const Complex &c)
{
m_fReal += c.m_fReal;
m_fImag += c.m_fImag;
return *this;
}
Complex& operator-= (const Complex &c)
{
m_fReal -= c.m_fReal;
m_fImag -= c.m_fImag;
return *this;
}
private:
double m_fReal;
double m_fImag;
//友元函数放在哪里无所谓,但要在类中声明
friend ostream& operator<< (ostream &os, const Complex &c);
friend istream& operator>> (istream &is, Complex &c);
};
ostream& operator<< (ostream &os, const Complex &c)
{
/*return os<<"[ " <<c.GetReal()<<" + "<<c.GetImag()<<"i ]"<<endl;*/
return os << "[ "<<c.m_fReal<<" + "<<c.m_fImag<<"i ]"<<endl;
// return os;
}
istream& operator>> (istream &is, Complex &c)
{
return is>>c.m_fReal>>c.m_fImag;
}
int main(void)
{
Complex c1(10,10);
Complex c2(20,20);
cout << "c1:" << c1 << "c2:" << c2;
/*
c1.Print();
c2.Print();
cout << "请输入实部和虚部:";
cin>>c1;
cout<<c1<<c2<<endl;
*/
/*
cout << c1 << c2;
Complex c3 = c1 + c2;
cout << c3;
Complex c4 = c3 - c2 - c1;
cout << c4;
*/
/*
Complex c3(30,30);
cout << "c3:" << c3 << endl;
c3 += c2 += c1;
cout << "c1:" << c1;
cout << "c2:" << c2;
cout << "c3:" << c3;
*/
/*
Complex c3(30,30);
cout << "c3:" << c3 << endl;
(c3 += c2) += c1;
cout << "c1:" << c1;
cout << "c2:" << c2;
cout << "c3:" << c3;
*/
//cout << "-c1:" << -c1;
/*
int n=10;
cout << ++++++++n << endl;// 14
//cout << n++++++++ << endl;// 错误
*/
cout << "++++++c1:" << ++++++c1 ;
cout << "c2++:" << c2++ ;
cout << "c2:" << c2;
//cout << "c2++++:" << c2++++;// 编译报错
return 0;
}