C++——this指针

水深无声 2022-04-17 03:57 358阅读 0赞

一 this指针的使用(成员函数中)

当通过一个对象调用成员函数时,编译器会把当前对象的地址传递给this指针;(this指针保存的是当前对象的地址)

  1. //this指针1
  2. #include<iostream.h>
  3. //定义一个点类
  4. class Point
  5. {
  6. private: //私有成员
  7. int x;
  8. int y;
  9. public:
  10. Point(int n,int m):x(n),y(m){} //构造函数
  11. void show() //成员函数
  12. {
  13. cout<<"x="<<x<<",y="<<y<<endl; //this指针的隐式使用
  14. cout<<"x="<<this->x<<",y="<<this->y<<endl; //this指针的显示使用
  15. cout<<"x="<<(*this).x<<",y="<<(*this).y<<endl; //this指针的显示使用
  16. }
  17. };
  18. int main()
  19. {
  20. Point p1(1,2);
  21. p1.show(); //this指针指向对象p1
  22. Point p2(3,4);
  23. p2.show(); //this指针指向对象p2
  24. return 0;
  25. }

二this指针的使用(非成员函数)

  1. //this指针2
  2. #include<iostream.h>
  3. //定义一个点类
  4. class Point
  5. {
  6. public: //公有成员
  7. int x;
  8. int y;
  9. public:
  10. Point(int n,int m):x(n),y(m){} //构造函数
  11. void show1();
  12. };
  13. void display(Point *m) //指针m保存的是p3的地址
  14. {
  15. //输出对象p3的x和y
  16. cout<<"x="<<m->x<<",y="<<m->y<<endl;
  17. }
  18. void Point ::show1() //在类体外实现show1函数
  19. {
  20. display(this); //this指针中存的是p3的地址;
  21. //调用了非成员函数display,将p3作为函数参数
  22. }
  23. int main()
  24. {
  25. Point p3(5,6);
  26. p3.show1(); //调用show1函数,对象p3的地址作为隐藏参数传递
  27. return 0;
  28. }

发表评论

表情:
评论列表 (有 0 条评论,358人围观)

还没有评论,来说两句吧...

相关阅读