回 帖 发 新 帖 刷新版面

主题:运算符重载

#include<iostream>
using namespace std;




class complex{
    float Real,Image;
public:
    complex(float r=0,float i=0){Real=r;Image=i;}
    float&AcessR(){return Real;}
    float&AcessI(){return Image;}
    void show()
    {cout<<Real;
         if(Image<0)cout<<Image<<'i'<<endl;
            else if(Image>0) cout<<'+'<<Image<<'i'<<endl;
              else cout<<endl;
     }
          complex operator +(complex&);
          complex operator -(complex&);
          complex operator +(float);
          complex operator +=(complex&);
          complex operator =(complex&);
          friend ostream&operator <<(ostream&,complex&);
          friend istream&operator >>(istream&,complex&);

    };

    complex complex ::operator +(complex &c)
    { complex t;
    t.Real=Real+c.Real;
    t.Image=Image+c.Image;
    return t;
    }




        complex complex ::operator -(complex &c)
    { complex t;
    t.Real=Real-c.Real;
    t.Image=Image-c.Image;
    return t;
    }


/*    complex complex ::operator +(float s)
    {return complex(Real+s,Image);}



    complex&complex::operator+=(complex &c)
    {Real+=c.Real;Image+=c.Image;
      return *this;
    }


    complex&complex::operator=(complex &c)
    {Real=c.Real;Image=c.Image;
      return *this;
    }




*/



      ostream&operator <<(ostream&os,complex&c)
      {os<<c.Real;
        if(c.Image)os<<'+'<<c.Image<<'i';
        else os<<c.Image<<'i';
        return os;
      }


      istream&operator>>(istream&is,complex&c)
      {
          is>>c.Real>>c.Image;
             return is;
      }






/**/

int main()
{ cout<<"是否进行数值计算,是请输入1否输入0:\n";
    bool t;
    cin>>t;
    if(t)
    { 
        int a,b;
           char op;
              cout<<"请输入数据格式(数字、符号、数字):";
          cin>>a>>op>>b;
       switch(op)
       {
         case '+':cout<<a<<'+'<<b<<'='<<a+b<<endl;break;
         case '-':cout<<a<<'-'<<b<<'='<<a-b<<endl;break;
         case '*':cout<<a<<'*'<<b<<'='<<a*b<<endl;break;
         case '/':cout<<a<<'/'<<b<<'='<<a/b<<endl;break;
       }
       
     }
       
     
    
          cout<<"是否进行向量运算,是请输入1否请输入0:\n";
         cin>>t;
      if(t)
      {complex c1,c2,c3;
         char po;

         cout<<"请输入数据(数字 数字 符号 数字 数字):\n";
         cin>>c1;
         cin>>po;
         cin>>c2;
                            //如果改为c3=c1+c2;
         switch(po)
         {
             case '+':cout<<c1<<'+'<<c2<<'='<<c1+c2<<endl;break; //把c1+c2改为c3为什么连接不成功
             case '-':cout<<c1<<'-'<<c2<<'='<<c1-c2<<endl;break; 
         
         
         
         
         }
        
      }
      else return 0;
    
    

return 0;
}
       

回复列表 (共3个回复)

沙发


望高手指教指教!!!

板凳

排版得像鬼画符

3 楼

长码段应该贴到pastie这类地方去

我来回复

您尚未登录,请登录后再回复。点此登录或注册