this指针

来源:互联网 发布:锐捷官网 for mac 编辑:程序博客网 时间:2024/06/07 10:11
this指针
this指针不是对象本身的一部分,不会影响到对象sizeof的结果。this的作用域在类内部,当类的非静态成员函数中访问类的非静态成员的时候,即使你没写上this指针,编译器会自动加上this。
使用:
1、返回*this,在类的非静态成员函数中返回对象本身的时候,直接使用return *this,注意此时函数返回的类型是该类的引用,如:Point& (Point是定义的类名);
2、当参数与成员变量同名时使用this指针。


#include<iostream>#include<vector>using namespace std;class point {private:int x;int y;public:point(int a, int b): x(a), y(b) { } int get_x_point() { return x;  }//x即this->xint get_y_point() { return y;  }//y即this->y void set_point(int x, int y) {this->x = x; //参数与成员变量同名是应用this指针 this->y = y;//x = x; //y = y;  }point& move_point(const point& point1) {x = point1.x;//this->x = point1.x;y = point1.y;//this->y = point1.y;return *this;} };int main() {point Point(2,2);cout << "before move_point:" << endl; cout << "x = " << Point.get_x_point() << endl;cout << "y = " << Point.get_y_point() <<endl;point Point2(3,3);Point = Point.move_point(Point2);cout << "after move_point:" << endl; cout << "x = " << Point.get_x_point() << endl;cout << "y = " << Point.get_y_point() <<endl;Point.set_point(4,4);cout << "after set_point:" << endl; cout << "x = " << Point.get_x_point() << endl;cout << "y = " << Point.get_y_point() <<endl;return 0;}



当把set_point换成
void set_point(int x, int y) {//this->x = x;  //this->y = y;x = x; //this->x = this->x;y = y; //this->y = this->y;//编译跟运行都可以进行,但是结果却不是我们所期待的,其结果仍然是上个点的坐标(3,3) }




原创粉丝点击