zoukankan      html  css  js  c++  java
  • 88.++ --的重载

    • shortsafe operator ++() 先自增再引用
    • shortsafe operator ++(int) 先引用再自增后面,需要副本(先用副本进行操作,然后再进行自己类的++改变数据)(返回的都是修改后的数据)
    • ()可以把对象名当做括号来操作

    代码示例

     1 #define _CRT_SECURE_NO_WARNINGS
     2 #include <iostream>
     3 using namespace std;
     4 
     5 //shortsafe operator ++() 先自增再引用
     6 //shortsafe operator ++(int) 先引用再自增后面,需要副本
     7 //()可以把对象名当做括号来操作
     8 
     9 class shortsafe
    10 {
    11 public:
    12     unsigned short sh = 0;
    13 public:
    14     //没有参数++或者--在前面(先自增再引用)
    15     shortsafe operator ++()
    16     {
    17         
    18         if (this->sh < 65535)
    19         {
    20             this->sh++;
    21         }
    22         else
    23         {
    24             abort();
    25         }
    26         return *this;
    27     }
    28 
    29     //后加(先引用再自增)
    30     shortsafe operator ++(int)
    31     {
    32         //先引用副本
    33         shortsafe tmp;
    34         tmp.sh = this->sh;
    35         if (this->sh < 65535)
    36         {
    37             this->sh++;
    38         }
    39         else
    40         {
    41             abort();
    42         }
    43         return tmp;
    44     }
    45 
    46     //前减(先自减再引用)
    47     void operator --()
    48     {
    49         if (this->sh >0)
    50         {
    51             this->sh++;
    52         }
    53         else
    54         {
    55             abort();
    56         }
    57     }
    58 
    59     unsigned short operator()()
    60     {
    61         return this->sh;
    62     }
    63 
    64     shortsafe operator +(unsigned int num)
    65     {
    66         shortsafe tmp;
    67         if (tmp.sh + num <= 65535)
    68         {
    69             tmp.sh += num;
    70         }
    71         else
    72         {
    73             abort();
    74         }
    75     }
    76 };
    77 
    78 
    79 void main()
    80 {
    81     shortsafe shsafe;
    82     shsafe.sh = 0;
    83     //重载不改变运算的优先级
    84     ++shsafe;
    85     cout << shsafe.sh << endl;
    86     cout << shsafe() << endl;
    87     cin.get();
    88 }
  • 相关阅读:
    telnet发邮件
    怎样接收电子邮件(POP3协议简介)(转载,写的很简洁)
    总结:string,char*,CString,int,WCHAR*之间的相互转换:
    文件查找
    SOAP消息机制简介
    jQuery 万能的选择器 NO.1
    数据库通用操作类
    jQuery (三) 管理jQuery包装集
    WebService Learning
    使用JQuery读取XML文件数据
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8596533.html
Copyright © 2011-2022 走看看