2010年10月20日 星期三

c++ operator overload

myClass.h
1 #include "myClass.h"
2
3 myClass operator+(myClass c, int i){
4 myClass tmp(c.value() + i);
5 return tmp;
6 }
7
8 myClass operator+(int i, myClass c){
9 myClass tmp(c.value() + i);
10 return tmp;
11 }
12
13 myClass operator-(myClass c, int i){
14 myClass tmp(c.value() - i);
15 return tmp;
16 }
17
18 myClass operator-(int i, myClass c){
19 myClass tmp(c.value() - i);
20 return tmp;
21 }
22
23 myClass operator++(myClass &c){
24 c.n++;
25 return c;
26 }
27
28 myClass operator++(myClass &c, int i){
29 myClass tmp(c.value());
30 c.n++;
31 return tmp;
32 }
33
34 myClass operator--(myClass &c){
35 c.n--;
36 return c;
37 }
38
39 myClass operator--(myClass &c, int i){
40 myClass tmp(c.value());
41 c.n--;
42 return tmp;
43 }




myClass.c
1 class myClass{
2 public:
3 myClass(){
4 n=0;
5 }
6
7 myClass(int in){
8 n = in;
9 }
10
11 myClass operator+(myClass c){//only for "myClass + myClass"
12 myClass tmp(n+c.value());
13 return tmp;
14 }
15
16 myClass operator-(myClass c){
17 myClass tmp(n-c.value());
18 return tmp;
19 }
20 /*
21 myClass& operator++(){//for ++myClass //& for reduce copy object?
22 n++;
23 return *this;//"this" is a pointer
24 }
25
26 myClass operator++(int i){//for myClass++
27 myClass tmp(n);
28 n++;
29 return tmp;
30 }
31
32 myClass& operator--(){
33 n--;
34 return *this;
35 }
36
37 myClass operator--(int){
38 myClass tmp(n);
39 n--;
40 return tmp;
41 }
42 */
43
44 friend myClass operator+(myClass c, int i); //for myClass + int
45
46 friend myClass operator+(int i, myClass c); //for int + myClass
47
48 friend myClass operator-(myClass c, int i);
49
50 friend myClass operator-(int i, myClass c);
51
52
53 friend myClass operator++(myClass &c);//for ++myClass
54
55 friend myClass operator++(myClass &c, int);//for myClass++
56
57 friend myClass operator--(myClass &c);//for --myClass
58
59 friend myClass operator--(myClass &c, int);//for myClass--
60
61 int value(){
62 return n;
63 }
64 private:
65 int n;
66 };

沒有留言: