this指针
来源:互联网 发布:锐捷官网 for mac 编辑:程序博客网 时间:2024/06/07 10:11
this指针
this指针不是对象本身的一部分,不会影响到对象sizeof的结果。this的作用域在类内部,当类的非静态成员函数中访问类的非静态成员的时候,即使你没写上this指针,编译器会自动加上this。
使用:
1、返回*this,在类的非静态成员函数中返回对象本身的时候,直接使用return *this,注意此时函数返回的类型是该类的引用,如:Point& (Point是定义的类名);
2、当参数与成员变量同名时使用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) }
- this指针
- this指针
- this指针
- this指针
- this指针
- this 指针
- this指针
- this指针----
- this指针
- this 指针
- This 指针
- this指针
- This指针
- this指针
- this指针
- this 指针
- this指针
- this指针
- unity3d--javascript的枚举类型写法
- Json日期格式的问题
- 浏览器 CSS hack
- hdu_1241 Oil Deposits
- 应用HttpClient来对付各种顽固的WEB服务器
- this指针
- Android Listener侦听的N种写法
- android NDK开发、编译、调试环境搭建与操作入门
- java时间差
- weakref的使用场景——实现缓存
- iOS中时间/日期处理NSDate的常用接口操作
- IOS中的frame 和 tableView的滑动问题
- hdu1398
- 解决Cannot load AMD 64-bit .dll