complex复数类

来源:互联网 发布:php 文件名截断 编辑:程序博客网 时间:2024/05/18 01:17
#include<iostream>
using  namespace std;
class complex
{
public:
 complex(int real = 0, int image = 0)
  :c_real(real)
  , c_image(image)
 {}
 complex &operator=(const complex &c1)    //c1是右操作数
 {
  if (this != &c1)
  {
   c_image = c1.c_image;
   c_real = c1.c_real;
  }
  return *this;
 }
 complex operator+(const complex &c1)
 {
  c_image += c1.c_image;
  c_real += c1.c_real;
  return *this; 
 }
 complex operator-(const complex &c1)
 {
  c_image -= c1.c_image;
  c_real -= c1.c_real;
  return *this;
 }
 complex operator*(const complex &c1)
 {
  complex temp;
  temp.c_real = c_real*c1.c_real - c_image*c1.c_image;
  temp.c_image  = c_real*c1.c_image + c1.c_real *c_image;
  return  temp;
 }
 complex &operator++()//前置++
 {
  c_real += 1;
  return  *this;
 }
 complex operator++(int)//后置++
 {
  complex temp;
  c_real++;
  return temp;
 }
 bool operator >(const complex& c1) //c1是右操作数
 {
  int i = 0;
  int j = 0;
  i = c1.c_real *c1.c_real + c1.c_image*c1.c_image;
  j = c_real *c_real + c_image*c_image;
  if (i < j)
  {
   return true;
  }
  else
  {
   return false;
  }
 }
 bool operator != (const complex& c1)
 {
  if ((c1.c_image != c_image) && (c1.c_real != c_real))
  {
   return true;
  }
  else
   return false;
 }
 bool operator  == (const complex& c1)
 {
  if ((c1.c_image == c_image) && (c1.c_real == c_real))
  {
   return true;
  }
  else
   return false;
 }
 friend   ostream& operator<<(ostream& _cout, const complex &c1)
 {
 
  _cout << c1.c_real<< "+" << c1.c_image<<"i" ;
  return _cout;
 }
private:
 int c_real;
 int c_image;
};
int main()
{
 complex c1(1, 2);
 complex c2(1, 2);
 //cout<< c1 + c2<<endl;
 //cout << c1 - c2<<endl;
 //cout <<c1 * c2<<endl;
 //++c1 ;
 //cout << c1<<endl;
 bool re1 = (c1==c2);   //在这里用一个布尔值去接收上面的返回值
 bool re2 = (c1 != c2);
 bool re3 = (c1 > c2);
 cout << re1<<endl;
 //cout << re2 << endl;
 //cout << re3 << endl;
 system("pause");
 return 0;
}
 在写的时候,我们也来一步步的测试,已验证代码的正确性
注意:在测试的时候要一步步的进行,在测试一个的时候要把其他的屏蔽掉,否则会影响测试结果。
0 0
原创粉丝点击