zoukankan      html  css  js  c++  java
  • c++重载前置++和--

    C语言中,前置和后置++,--都不能作为左值,而在c++中,前置的++和--可以作为左值,从下面的重载运算符中也可以看出,它们返回的是引用,我不知道为什么这里和c语言中不同,但c++类似的提升还有三目运算符?:,在c中也不可以做左值,但c++中可以。或者是因为c++提出了引用,进而对c做了一定的提升吧。

    重载前置++和--,分别采用成员函数和全局函数的方式实现,代码如下:重载运算符的行为应该和内置类型一致,所以前置的++、--应该返回引用。

     1 #include<iostream>
     2 using namespace std;
     3 class Test {
     4     friend Test & operator--(Test &obj);
     5 public:
     6     Test(int a = 0, int b = 0)
     7     {
     8         this->a = a;
     9         this->b = b;
    10     }
    11     void display()
    12     {
    13         cout << "a:" << a << " b:" << b << endl;
    14     }
    15 public:
    16     Test & operator++()
    17     {
    18         this->a++;
    19         this->b++;
    20         return *this;
    21     }
    22 private:
    23     int a;
    24     int b;
    25 };
    26 Test & operator--(Test &obj)
    27 {
    28     obj.a--;
    29     obj.b--;
    30     return obj;
    31 }
    32 int main()
    33 {
    34     Test t1(1, 2);
    35     t1.display();
    36     ++t1;
    37     t1.display();
    38     --t1;
    39     t1.display();
    40     cout << "hello world!
    ";
    41     return 0;
    42 }

    recommend:

    1.赋值(=)、下标([])、调用和成员访问箭头(->)运算符必须是成员函数;

    2.复合赋值运算符一般来说应该是成员,但并非必须,这一点与赋值运算符略有不同;

    3.改变对象状态的运算符或者与给定类型密切相关的运算符,如递增、递减和解引用运算符,通常应该是成员(上述代码只是为了复习训练一下全局函数和成员的分别实现,所以没有遵循这条规则);

    4.具有对称性的运算符可能转换任一端的运算对象,例如算术、相等性、关系和位运算符等,因此它们通常应该是普通的非成员函数。

     总结下来就是,只用记住第四点,其他情况都用成员函数的方式。

  • 相关阅读:
    Nim or not Nim? hdu3032 SG值打表找规律
    Maximum 贪心
    The Super Powers
    LCM Cardinality 暴力
    Longge's problem poj2480 欧拉函数,gcd
    GCD hdu2588
    Perfect Pth Powers poj1730
    6656 Watching the Kangaroo
    yield 小用
    wpf DropDownButton 源码
  • 原文地址:https://www.cnblogs.com/yangguang-it/p/6484525.html
Copyright © 2011-2022 走看看