angelpan1014

 

++的前置和后置

C++编译器是根据运算符函数参数表里是否插入了关键字int来区分是++是前置还是后置的,例如:

     1  #include<iostream>
     2  using namespace std;
     3  class TDpoint
     4  {
     5          public:
     6                  TDpoint(int x=0,int y=0,int z=0)
     7                  {
     8                          this->x=x;
     9                          this->y=y;
    10                         this->z=z;
    11                  }
    12                  TDpoint operator++();
    13                  TDpoint operator++(int);
    14                  friend TDpoint operator++(TDpoint& point);
    15                  friend TDpoint operator++(TDpoint& point,int);
    16                  void showpoint();
    17
    18          private:
    19                          int x;
    20                          int y;
    21                          int z;
    22  };
    23
    24  TDpoint TDpoint::operator++()
    25  {
    26          ++this->x;
    27          ++this->y;
    28          ++this->z;
    29          return *this;
    30  }
    31
    32  TDpoint TDpoint::operator++(int)
    33  {
    34          TDpoint point(*this);
    35          this->x++;
    36          this->y++;
    37          this->z++;
    38          return point;
    39  }
    40
    41  TDpoint operator++(TDpoint & point)
    42  {
    43          ++point.x;
    44          ++point.y;
    45          ++point.z;
    46          return point;
    47  }
    48
    49  TDpoint operator++(TDpoint & point,int)
    50  {
    51          TDpoint poins(point);
    52          point.x++;
    53          point.y++;
    54          point.z++;
    55          return poins;
    56
    57  }
    58
    59
    60  void TDpoint::showpoint()
    61  {
    62          cout<<"("<<x<<","<<y<<","<<z<<")"<<endl;
    63  }
    64
    65  int main()
    66  {
    67          TDpoint points(1,1,1);
    68          points.operator++();
    69          points.showpoint();
    70
    71          points=points.operator++(0);
    72          points.showpoint();
    73
    74          operator++(points);
    75          points.showpoint();
    76
    77          points=operator++(points,0);
    78          points.showpoint();
    79
    80          return 0;
    81
    82  }

输出的结果是:

(2,2,2)
(2,2,2)
(3,3,3)
(3,3,3)

但是,如果将main改成如下的:

 

int main()
{
        TDpoint points(1,1,1);
        points.operator++();
        points.showpoint();

 

        points.operator++(0);
        points.showpoint();

 

        operator++(points);
        points.showpoint();

 

        operator++(points,0);
        points.showpoint();

 

        return 0;

 

}

 

则输出:

(2,2,2)
(3,3,3)
(4,4,4)
(5,5,5)

 

posted on 2012-07-27 09:25  angelpan1014  阅读(154)  评论(0编辑  收藏  举报

导航