8-10

编写程序定义类Point,有数据成员x,y.为其定义友元函数实现重载“+”。

 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     unsigned  x;
10     unsigned  y;
11 public:
12     Point():x(0),y(0){}
13     Point(unsigned x, unsigned y):x(x), y(y){}
14     unsigned GetX()const{return x;}
15     unsigned GetY()const{return y;}
16     void show(){cout<<"x:"<<x<<" "<<"y:"<<y<<endl;}
17     friend Point operator +(Point& p, int n);
18     friend Point operator +(int n, Point& p);
19 };
20 
21 Point operator +(Point& p, int n){
22     Point temp = p;
23     temp.x += n;
24     temp.y += n;
25     return temp;
26 }
27 
28 Point operator +(int n, Point& p){
29     Point temp = p;
30     temp.x += n;
31     temp.y += n;
32     return temp;
33 }
34 
35 
36 
37 int main(){
38     Point p(1, 2);
39     p.show();
40     p = p + 5;
41     p.show();
42     p = 5 + p;
43     p.show();
44     return 0;
45 }

 

posted @ 2023-03-18 23:30  nlkdfgnvfdkl  阅读(50)  评论(0)    收藏  举报