• 重载单目运算符以及重载运算符的注意事项


    一、单目运算符的重载

    单目运算符可分为两种:

    1)可以放在前面,也可以放在后面的单目,如:++ -- 

    2)只能放在前面的运算符:! +(正号) -(负号)&  ~   ()

    3)只能放到后面的运算符:*  -> 

    重载单目运算符方法有两种: 类成员重载以及友元函数重载。

    具体形式如下:

     入参和返回值根据单目运算符的特性进行选择,导图只是一个通用形式,明白意思就行。

     上代码:

    1. #include
    2. #include
    3. using namespace std;
    4. class Interger
    5. {
    6. public:
    7. Interger(int d=0):m_nData(d){}
    8. void operator--(int)
    9. {
    10. this->m_nData--;
    11. cout<
    12. cout << "operator--(int)"<< endl;
    13. }
    14. void operator++(int)
    15. {
    16. this->m_nData++;
    17. cout<
    18. cout << "operator++(int)"<< endl;
    19. }
    20. void operator++()
    21. {
    22. this->m_nData = this->m_nData+2;
    23. cout<
    24. cout << "operator++()"<< endl;
    25. }
    26. void show()
    27. {
    28. cout<
    29. }
    30. private:
    31. int m_nData;
    32. public:
    33. friend ostream& operator<<(ostream& os, Interger& input );
    34. friend Interger& operator!(Interger& input);
    35. };
    36. ostream& operator<<(ostream& os, Interger& input )
    37. {
    38. return os<
    39. }
    40. Interger& operator!(Interger& input)
    41. {
    42. input.m_nData = !input.m_nData;
    43. cout << "operator!()"<< endl;
    44. cout<< input.m_nData <
    45. return input;
    46. }
    47. int main(int argc, char *argv[])
    48. {
    49. QCoreApplication a(argc, argv);
    50. Interger aa;
    51. aa--;
    52. ++aa;
    53. aa++;
    54. !aa;
    55. return a.exec();
    56. }

    运行结果

    二、运算符重载重载注意事项:

    1,以下运算符不能重载

            ?:  .   ::  sizeof   && || & |

    2,不能发明运算符

           比如 @

    3,不能改变运算符的特性,符合队形的运算属性。

    4,不能重载基本类型的运算,重载时至少要有一个是类类型。

    5,只能重载成全局运算符的运算符

            第一个操作数是C++预定义类型 <<   >>  ostream istream类型

            第一个操作数是基本类型

    6,只能重载成成员函数的运算符

            1)=(+= -= *=)   ---- 赋值运算符

            2)[]  ---------------数组对象(把对象当数组用)

            3)() ----------------强转,函数对象(把对象当函数使用)

            4)-> *  -------------指针对象(把对象当指针使用) 

  • 相关阅读:
    Python:实现quantum entanglement量子纠缠技术算法(附完整源码)
    快速入门C++第四天——继承与派生
    flink理论干货笔记(7)及spark论文相关思考
    Spring原理:PostProcessor与AOP原理
    【C++】函数重载 ① ( 函数重载概念 | 函数重载判断标准 - 参数个数 / 类型 / 顺序 | 返回值不是函数重载判定标准 )
    Mybatis-plus中Service和Mapper
    Linux vi和vim编辑器、快捷键的使用
    CEAC之《企业信息管理》2
    五、函数的调用过程
    [kingbase运维之奇怪的现象]
  • 原文地址:https://blog.csdn.net/yjj350418592/article/details/127978098