Code:
1: // Listing 10.11
2: // Returning the dereferenced this pointer
3:
4: typedef unsigned short USHORT;
5: #include <iostream.h>
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: void Increment() { ++itsVal; }
15: const Counter& operator++ ();
16:
17: private:
18: USHORT itsVal;
19:
20: };
21:
22: Counter::Counter():
23: itsVal(0)
24: {};
25:
26: const Counter& Counter::operator++()
27: {
28: ++itsVal;
29: return *this;
30: }
31:
32: int main()
33: {
34: Counter i;
35: cout << "The value of i is " << i.GetItsVal() << endl;
36: i.Increment();
37: cout << "The value of i is " << i.GetItsVal() << endl;
38: ++i;
39: cout << "The value of i is " << i.GetItsVal() << endl;
40: Counter a = ++i;
41: cout << "The value of a: " << a.GetItsVal();
42: cout << " and i: " << i.GetItsVal() << endl;
48: return 0;
49: }
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
1: // Listing 10.11
2: // Returning the dereferenced this pointer
3:
4: typedef unsigned short USHORT;
5: #include <iostream.h>
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: void Increment() { ++itsVal; }
15: const Counter& operator++ ();
16:
17: private:
18: USHORT itsVal;
19:
20: };
21:
22: Counter::Counter():
23: itsVal(0)
24: {};
25:
26: const Counter& Counter::operator++()
27: {
28: ++itsVal;
29: return *this;
30: }
31:
32: int main()
33: {
34: Counter i;
35: cout << "The value of i is " << i.GetItsVal() << endl;
36: i.Increment();
37: cout << "The value of i is " << i.GetItsVal() << endl;
38: ++i;
39: cout << "The value of i is " << i.GetItsVal() << endl;
40: Counter a = ++i;
41: cout << "The value of a: " << a.GetItsVal();
42: cout << " and i: " << i.GetItsVal() << endl;
48: return 0;
49: }
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
Citat:
As discussed above, if the Counter object allocated memory, it would be important to override the copy constructor. In this case, the default copy constructor works fine.
Molim Vas, kada se to ovde poziva default copy konstruktor, kada se objekat predaje po referenci ?
Hvala