8-7

对类Point重载“++”(自增)、“--”(自减)运算符,要求同时重载前缀和后缀的形式。

 1 #include <iostream>
 2 #include <string>
 3 #include<string.h>
 4 #include <stdio.h>
 5 using namespace std;
 6 
 7 class Point{
 8 private:
 9     int x;
10     int y;
11 public:
12     Point();
13     Point(int, int);
14     ~Point(){}
15     void ShowPoint(){cout<<"x:"<<x<<" "<<"y:"<<y<<endl;}
16     Point& operator ++();
17     Point operator ++(int);
18     Point& operator --();
19     Point operator --(int);
20 };
21 
22 Point::Point():x(0), y(0){}
23 
24 Point::Point(int x, int y):x(x), y(y){}
25 
26 Point& Point::operator ++(){
27     x++;
28     y++;
29     return *this;
30 }
31 
32 Point Point::operator ++(int){
33     Point temp = *this;
34     ++*this;
35     return temp;
36 }
37 
38 Point& Point::operator --(){
39     x--;
40     y--;
41     return *this;
42 }
43 
44 Point Point::operator --(int){
45     Point temp = *this;
46     --*this;
47     return temp;
48 }
49 
50 
51 int main(){
52     Point p(1,2);
53     p.ShowPoint();
54     (p++).ShowPoint();
55     (++p).ShowPoint();
56     (p--).ShowPoint();
57     (--p).ShowPoint();
58     return 0;    
59 }

 

posted @ 2023-03-17 23:01  nlkdfgnvfdkl  阅读(112)  评论(0)    收藏  举报