C++ 常用的运算符重载

重定义或重载大部分 C++ 内置的运算符

  1. 函数名是由关键字 operator 和其后要重载的运算符符号构成的。如下
     类名 operator+(const 类名&);
    

可重载运算符/不可重载运算符

  1. 下面是可重载的运算符列表:

     双目算术运算符	+ (加),-(减),*(乘),/(除),% (取模)
     关系运算符		==(等于),!= (不等于),< (小于),> (大于>,<=(小于等于),>=(大于等于)
     逻辑运算符		||(逻辑或),&&(逻辑与),!(逻辑非)
     单目运算符		+ (正),-(负),*(指针),&(取地址)
     自增自减运算符	++(自增),--(自减)
     位运算符			| (按位或),& (按位与),~(按位取反),^(按位异或),,<< (左移),>>(右移)
     赋值运算符		=, +=, -=, *=, /= , % = , &=, |=, ^=, <<=, >>=
     空间申请与释放	new, delete, new[ ] , delete[]
     其他运算符		()(函数调用),->(成员访问),,(逗号),[](下标)
    
  2. 下面是不可重载的运算符列表:

     .            :成员访问运算符
     .*, ->*      :成员指针访问运算符
     ::           :域运算符
     sizeof       :长度运算符
     ?:           :条件运算符
     #            : 预处理符号
    
一元运算符重载
  1. 操作符如下

     1. 递增运算符( ++ )和递减运算符( -- )
     2. 一元减运算符,即负号( - )
     3. 逻辑非运算符( ! )
    

<1> 递增运算符( ++ ) 重载。(- -)类似
Code:

#include <iostream>
using namespace std;
 
class Time
{
   private:
      int hours;             // 0 到 23
      int minutes;           // 0 到 59
   public:
      // 所需的构造函数
      Time(){
         hours = 0;
         minutes = 0;
      }
      Time(int h, int m){
         hours = h;
         minutes = m;
      }
      // 显示时间的方法
      void displayTime()
      {
         cout << "H: " << hours << " M:" << minutes <<endl;
      }
      // 重载前缀递增运算符( ++ )如(++Time;)
      Time operator++ ()  
      {
         ++minutes;          // 对象加 1
         if(minutes >= 60)  
         {
            ++hours;
            minutes -= 60;
         }
         return Time(hours, minutes);
      }
      // 重载后缀递增运算符( ++ )如(Time++;)
      Time operator++( int )         
      {
         // 保存原始值
         Time T(hours, minutes);
         // 对象加 1
         ++minutes;                    
         if(minutes >= 60)
         {
            ++hours;
            minutes -= 60;
         }
         // 返回旧的原始值
         return T; 
      }
};

int main()
{
   Time T1(11, 59), T2(10,40), T3; 
   ++T1;                    // T1 加 1, 前缀自增
   T1.displayTime();        // 显示 T1
   
   T2++;                    // T2 再加 1,  后缀自增
   T2.displayTime();        // 显示 T2
   return 0;
   
   T3= ++T1;                    // T1 加 1赋给T3,  后缀自增
   T3.displayTime();        // 显示 T2
   return 0;
}

结果:

H: 12 M:0 
H: 10 M:41
H: 12 M:1 

<2> 一元减运算符( - )重载。
Code:

class Distance
{
   private:
      int feet;             // 0 到无穷
      int inches;           // 0 到 12
   public:
      // 所需的构造函数
      Distance(){
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i){
         feet = f;
         inches = i;
      }
      // 显示距离的方法
      void displayDistance()
      {
         cout << "F: " << feet << " I:" << inches <<endl;
      }
      //---------------------------------------------------
      // 重载负运算符( - )
      Distance operator- ()  
      {
      	//每个元素都取反数
         feet = -feet;
         inches = -inches;
         return Distance(feet, inches);
      }
      //--------------------------------------
};

int main()
{
   Distance D1(11, 10);//构造器初始化
 
   -D1;                     // 取相反数
    D1.displayDistance();    // 距离 D1
   return 0;
}
结果
F: -11 I:-10
二元运算符重载
  1. 操作符如下

     加运算符( + )、减运算符( - )、乘运算符( * )和除运算符( / ) 
    

    <1> 二元减运算符( + )重载。
    Code:

    #include <iostream>
    using namespace std;
     
    class Box
    {
       double length;      // 长度
       double breadth;     // 宽度
       double height;      // 高度
    public:
     
       double getVolume(void)
       {
          return length * breadth * height;
       }
       void setLength( double len )
       {
           length = len;
       }
     
       void setBreadth( double bre )
       {
           breadth = bre;
       }
     
       void setHeight( double hei )
       {
           height = hei;
       }
       // 重载 + 运算符,用于把两个 Box 对象相加
       Box operator+(const Box& b)  //下面是把 + 后面的对象 作为实参
       {
          Box box;
          box.length = this->length + b.length;
          box.breadth = this->breadth + b.breadth;
          box.height = this->height + b.height;
          return box;
       }
      /* 这种也行,友元函数
       friend Box operator+(const Box& a, const Box& b)
       {
    	    Box box;
    	    box.length = a.length + b.length;
    	    box.breadth = a.breadth + b.breadth;
    	    box.height = a.height + b.height;
    	    // cout << box.length << "--" << box.breadth << "--" << box.height << endl; 
    	    return box;
      }*/
    };
    // 程序的主函数
    int main( )
    {
       Box Box1;                // 声明 Box1,类型为 Box
       Box Box2;                // 声明 Box2,类型为 Box
       Box Box3;                // 声明 Box3,类型为 Box
       double volume = 0.0;     // 把体积存储在该变量中
     
       // Box1 详述
       Box1.setLength(6.0); 
       Box1.setBreadth(7.0); 
       Box1.setHeight(5.0);
     
       // Box2 详述
       Box2.setLength(12.0); 
       Box2.setBreadth(13.0); 
       Box2.setHeight(10.0);
     
       // Box1 的体积
       volume = Box1.getVolume();
       cout << "Volume of Box1 : " << volume <<endl;
     
       // Box2 的体积
       volume = Box2.getVolume();
       cout << "Volume of Box2 : " << volume <<endl; 
     
       // 把两个对象相加,得到 Box3
       Box3 = Box1 + Box2;//相当于把Box2作为参数 => Box3=Box1.operator+(Box2); 
     
       // Box3 的体积
       volume = Box3.getVolume();
       cout << "Volume of Box3 : " << volume <<endl;
     
       return 0;
    }
    

结果:

Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
输入/输出运算符重载
  1. 操作符如下

     重载提取运算符 >> 和插入运算符 << 
    

    <1> 提取运算符 >> 和插入运算符 << 重载。
    Code:

    #include <iostream>
    using namespace std;
     
    class Distance
    {
       private:
          int feet;             // 0 到无穷
          int inches;           // 0 到 12
       public:
          // 所需的构造函数
          Distance(){
             feet = 0;
             inches = 0;
          }
          Distance(int f, int i){
             feet = f;
             inches = i;
          }
          friend ostream &operator<<( ostream &output, const Distance &D )
          { 
             output << "F : " << D.feet << " I : " << D.inches;
             return output;            
          }
     
          friend istream &operator>>( istream  &input, Distance &D )
          { 
             input >> D.feet >> D.inches;
             return input;            
          }
    };
    int main()
    {
       Distance D1(11, 10), D2(5, 11), D3;
     
       cout << "Enter the value of object : " << endl;
       cin >> D3;
       cout << "First Distance : " << D1 << endl;//重载的本质没变,只是形式变了而已
       cout << "Second Distance :" << D2 << endl;
       cout << "Third Distance :" << D3 << endl;
     
     
       return 0;
    }
    

结果:

Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I : 10
赋值运算符重载
  1. 操作符如下

     (=)用于创建一个对象,比如拷贝构造函数
    

    <1> 赋值运算符(=)重载。
    Code:

#include <iostream>
using namespace std;
 
class Distance
{
   private:
      int feet;             // 0 到无穷
      int inches;           // 0 到 12
   public:
      // 所需的构造函数
      Distance(){
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i){
         feet = f;
         inches = i;
      }
      void operator=(const Distance &D )
      { 
         feet = D.feet;
         inches = D.inches;
      }
      // 显示距离的方法
      void displayDistance()
      {
         cout << "F: " << feet <<  " I:" <<  inches << endl;
      }
      
};
int main()
{
   Distance D1(11, 10), D2(5, 11);
 
   cout << "First Distance : "; 
   D1.displayDistance();
   cout << "Second Distance :"; 
   D2.displayDistance();
 
   // 使用赋值运算符
   D1 = D2; //这个=重载不一样,不是D1指向D2的对象,而是将D2成员的值给了D1成员,对象不变。
   cout << "First Distance :"; 
   D1.displayDistance();
 
   return 0;
}

结果:

First Distance : F: 11 I:10
Second Distance :F: 5 I:11
First Distance :F: 5 I:11
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值