关键词搜索

源码搜索 ×
×

C++中的this指针究竟是什么?

发布2013-05-15浏览7704次

详情内容

      先来看一个简单的程序:

 

  1. #include <iostream>
  2. using namespace std;
  3. class Human
  4. {
  5. private:
  6. int age;
  7. public:
  8. void setAge(int a)
  9. {
  10. age = a;
  11. }
  12. int getAge()
  13. {
  14. return age;
  15. }
  16. };
  17. int main()
  18. {
  19. Human h;
  20. h.setAge(10);
  21. cout << h.getAge() << endl; // 10
  22. return 0;
  23. }

     稍微改动上述程序,得到:

 

 

  1. #include <iostream>
  2. using namespace std;
  3. class Human
  4. {
  5. private:
  6. int age;
  7. public:
  8. void setAge(int age)
  9. {
  10. age = age; // 真正的字段age被形参age屏蔽
  11. }
  12. int getAge()
  13. {
  14. return age;
  15. }
  16. };
  17. int main()
  18. {
  19. Human h;
  20. h.setAge(10);
  21. cout << h.getAge() << endl; // -858993460
  22. return 0;
  23. }

      那怎么办呢?用this指针吧:

  1. #include <iostream>
  2. using namespace std;
  3. class Human
  4. {
  5. private:
  6. int age;
  7. public:
  8. void setAge(int age)
  9. {
  10. this->age = age;
  11. }
  12. int getAge()
  13. {
  14. return age;
  15. }
  16. };
  17. int main()
  18. {
  19. Human h;
  20. h.setAge(10);
  21. cout << h.getAge() << endl; // 10
  22. return 0;
  23. }

     实际上,在编译器看来,成员函数setAge是这样的:void setAge(Human *const this, int age); 也就是说this指针是编译器默认的成员函数的一个参数,在调用h.setAge(10);时,在编译看来,实际上是调用了Human::setAge(&h, 10); 这样,就实现了对象与其对应的属性或方法的绑定。下面这个程序之所以能区分不同不同对象,也完全是拜this指针所赐。

 

 

  1. #include <iostream>
  2. using namespace std;
  3. class Human
  4. {
  5. private:
  6. int age;
  7. public:
  8. void setAge(int a)
  9. {
  10. age = a;
  11. }
  12. int getAge()
  13. {
  14. return age;
  15. }
  16. };
  17. int main()
  18. {
  19. Human h1, h2;
  20. h1.setAge(10);
  21. cout << h1.getAge() << endl; // 10
  22. h2.setAge(20);
  23. cout << h2.getAge() << endl; // 20
  24. return 0;
  25. }

     接着来欣赏如下程序:

 

 

  1. #include <iostream>
  2. using namespace std;
  3. class Human
  4. {
  5. private:
  6. int age;
  7. public:
  8. void setAge(int a)
  9. {
  10. cout << this << endl; // 0012FF7C
  11. age = a;
  12. cout << age << endl; // 10
  13. }
  14. int getAge()
  15. {
  16. return age;
  17. }
  18. };
  19. int main()
  20. {
  21. Human h;
  22. cout << &h << endl; // 0012FF7C
  23. h.setAge(10);
  24. cout << h.getAge() << endl; // 10
  25. return 0;
  26. }

     this指针是指向对象的,而静态成员函数并不属于某个对象,因此,在静态成员函数中,并没有this指针,这一点值得注意。
 

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载