1: // Listing 10.12
2: // Returning the dereferenced this pointer
3:
4: #include <iostream.h>
5: typedef unsigned short USHORT;
6:
7: class Counter
8: {
9: public:
10: Counter();
11: ~Counter(){}
12: USHORT GetItsVal()const { return itsVal; }
13: void SetItsVal(USHORT x) {itsVal = x; }
14: const Counter& operator++ (); // prefix
15: const Counter operator++ (int); // postfix
16:
17: private:
18: USHORT itsVal;
19: };
20:
21: Counter::Counter():
22: itsVal(0)
23: {}
24:
25: const Counter& Counter::operator++()
26: {
27: ++itsVal;
28: return *this;
29: }
30:
31: const Counter Counter::operator++(int)
32: {
33: Counter temp(*this);
34: ++itsVal;
35: return temp;
36: }
37:
38: int main()
39: {
40: Counter i;
41: cout << "The value of i is " << i.GetItsVal() << endl;
42: i++;
43: cout << "The value of i is " << i.GetItsVal() << endl;
44: ++i;
45: cout << "The value of i is " << i.GetItsVal() << endl;
46: Counter a = ++i;
47: cout << "The value of a: " << a.GetItsVal();
48: cout << " and i: " << i.GetItsVal() << endl;
49: a = i++;
50: cout << "The value of a: " << a.GetItsVal();
51: cout << " and i: " << i.GetItsVal() << endl;
52: return 0;
53: }
Output: The value of i is 0
The value of i is 1
The value of i is 2
The value of a: 3 and i: 3
The value of a: 3 and i: 4
Analysis: The postfix operator is declared on line 15 and implemented on lines 31-36. Note that the call to the prefix operator on line 14 does not include the flag integer (x), but is used with its normal syntax. The postfix operator uses a flag value (x) to signal that it is the postfix and not the prefix. The flag value (x) is never used, however.
NIJE MI JASNO, zasto kaze da postfiksni operator koristi zastavicu (x) kad zadnja recenica kaze nikada se ne koristi?
I gdje je ta uopce zastavica u ovom KOD-u?
I ovaj dio KOD-a se nikako ne koristi izgleda: void SetItsVal(USHORT x) {itsVal = x; } ???
Unaprijed hvala na vasem odgovoru!