先来看一个简单的程序:
- #include <iostream>
- using namespace std;
-
- class Human
- {
- private:
- int age;
-
- public:
- void setAge(int a)
- {
- age = a;
- }
-
- int getAge()
- {
- return age;
- }
- };
-
- int main()
- {
- Human h;
- h.setAge(10);
- cout << h.getAge() << endl; // 10
-
- return 0;
- }
稍微改动上述程序,得到:
- #include <iostream>
- using namespace std;
-
- class Human
- {
- private:
- int age;
-
- public:
- void setAge(int age)
- {
- age = age; // 真正的字段age被形参age屏蔽
- }
-
- int getAge()
- {
- return age;
- }
- };
-
- int main()
- {
- Human h;
- h.setAge(10);
- cout << h.getAge() << endl; // -858993460
-
- return 0;
- }
那怎么办呢?用this指针吧:
- #include <iostream>
- using namespace std;
-
- class Human
- {
- private:
- int age;
-
- public:
- void setAge(int age)
- {
- this->age = age;
- }
-
- int getAge()
- {
- return age;
- }
- };
-
- int main()
- {
- Human h;
- h.setAge(10);
- cout << h.getAge() << endl; // 10
-
- return 0;
- }
实际上,在编译器看来,成员函数setAge是这样的:void setAge(Human *const this, int age); 也就是说this指针是编译器默认的成员函数的一个参数,在调用h.setAge(10);时,在编译看来,实际上是调用了Human::setAge(&h, 10); 这样,就实现了对象与其对应的属性或方法的绑定。下面这个程序之所以能区分不同不同对象,也完全是拜this指针所赐。
- #include <iostream>
- using namespace std;
-
- class Human
- {
- private:
- int age;
-
- public:
- void setAge(int a)
- {
- age = a;
- }
-
- int getAge()
- {
- return age;
- }
- };
-
- int main()
- {
- Human h1, h2;
- h1.setAge(10);
- cout << h1.getAge() << endl; // 10
-
- h2.setAge(20);
- cout << h2.getAge() << endl; // 20
-
- return 0;
- }
接着来欣赏如下程序:
- #include <iostream>
- using namespace std;
-
- class Human
- {
- private:
- int age;
-
- public:
- void setAge(int a)
- {
- cout << this << endl; // 0012FF7C
- age = a;
- cout << age << endl; // 10
- }
-
- int getAge()
- {
- return age;
- }
- };
-
- int main()
- {
- Human h;
- cout << &h << endl; // 0012FF7C
- h.setAge(10);
- cout << h.getAge() << endl; // 10
-
- return 0;
- }
this指针是指向对象的,而静态成员函数并不属于某个对象,因此,在静态成员函数中,并没有this指针,这一点值得注意。