this is a special pointer used inside member functions to point to the object itself. *this (this dereferenced) represents the "current" object. this is the address of the object. this is most commonly used to return by reference.
Example 5-1 - The this Pointer
1 // File: ex5-1.cpp - the this pointer
2 #include <iostream>
3 using namespace std;
4
5 class thing {
6 int eger;
7 double mint;
8 public:
9 thing(int x = 0, double y = 0.0); // constructor
10 void copy(thing&);
11 void show(void) { cout << eger << ' ' << mint << endl;}
12 };
13
14 thing::thing(int x, double y) {
15 eger = x;
16 mint = y;
17 }
18
19 void thing::copy(thing& z) {
20 if (this == &z) {
21 cout << "Don't copy me to myself\n";
22 return;
23 }
24 eger = z.eger;
25 mint = z.mint;
26 }
27
28 int main(void) {
29 thing a(5,3.14);
30 thing b(1);
31 thing c;
32 a.show(); // displays 5 3.14
33 b.show(); // displays 1 0
34 c.show(); // displays 0 0
35 c.copy(a);
36 c.show(); // displays 5 3.14
37 b.copy(b); // displays Don't copy me to myself
38 b.show(); // displays 1 0
39 return 0;
40 }
沒有留言:
張貼留言