信管14:运算符重载示例一

本文详细解释了如何在C++中为复数类实现加、减、乘运算符重载,并通过实例展示了如何使用这些重载运算符进行复数的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
1.首先理解运算符
2.掌握重载运算函数定义格式*/
#include<iostream>
using namespace std;


class complex {
  public:
   double real, imag;
   complex(double r=0,double i=0)
    {real=r;imag=i;} 
};


 complex operator+(complex co1,complex co2)   //重新定义运算符函数 operator+()
 {complex temp;                               //运算符函数 operator+()和类有啥关系?
  temp.real=co1.real+co2.real;
  temp.imag=co1.imag+co2.imag;
  return temp; 
 }


 complex operator-(complex co1,complex co2)  //重新定义运算符函数 operator-()
 {complex temp;
  temp.real=co1.real-co2.real;
  temp.imag=co1.imag-co2.imag;
  return temp; 
 }


  complex operator*(complex co1,complex co2)  //重新定义运算符函数 operator*()
 {complex temp;
  temp.real=co1.real*co2.real-co1.imag*co2.imag;
  temp.imag=co1.real*co2.imag+co1.imag*co2.real;
  return temp; 
 }


 int main( ) 
{  int i1=11,i2=22;
   float f1=1.1,f2=2.2;
   double d1=1.11,d2=2.22;

   int i=+(i1,i2);  // i=i1+i2;
   float f=+(f1,f2);
   double d=(d1,d2);
   cout<<"i="<<i<<"  f= "<<f<<"  d= "<<d<<endl;  //有什么启示?

    i=-(i1,i2);
    f=-(f1,f2);
    d=-(d1,d2);
    cout<<"i="<<i<<"  f= "<<f<<"  d= "<<d<<endl;

   complex com1(1.1,2.2),com2(3.3,4.4),total1,total2;

   cout<<"two complex add: "<<endl;
    total1=operator+(com1,com2);   
    cout<<"  real1="<<total1.real<<" imag1=" <<total1.imag <<endl;

    total2=com1+com2; 
    cout<<"  real2="<<total2.real<<" imag2="<<total2.imag <<endl;

   cout<<"two complex sub: "<<endl;
   total1=operator-(com1,com2);   
    cout<<"real1="<<total1.real<<" imag1=" <<total1.imag <<endl;

    total2=com1-com2; 
    cout<<"  real2="<<total2.real<<" imag2="<<total2.imag <<endl;

    cout<<"two complex multiply :"<<endl;
    total1=operator*(com1,com2);   
    cout<<"  real1="<<total1.real<<" imag1=" <<total1.imag <<endl;

    total2=com1*com2; 
    cout<<"  real2="<<total2.real<<" imag2="<<total2.imag <<endl;

    system("pause");
return 0;  
 

 }

/*  此程序复数类的定义存在什么问题?*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值