目录
一、关于this指针的一个经典问题
二、this指针的特点
(一)本质
(二)应用
1. 不使用this指针
2. 使用this指针
3. 两者代码对比
三、代码举例
1. 举例1
2. 举例2
一、关于this指针的一个经典问题
当你进入一个房子后,
你可以看见桌子、椅子、地板等,
但是房子你是看不到全貌了。
对于一个类的实例来说,
你可以看到它的成员函数、成员变量,
但是实例本身呢?
this是一个指针,它时时刻刻指向你这个实例本身
二、this指针的特点
- this指针的类型:类类型* const,即成员函数中,不能给this指针赋值
- 只能在“成员函数”的内部使用
- this指针本质上是“成员函数”的形参,当对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针
- this指针是“成员函数”第一个隐含的指针形参,通常this指针在系统中是隐含存在的,也可以把它显式表示出来
- 非静态成员函数中可以直接使用this来代表指向该函数作用对象的指针,静态成员函数中不能使用this指针,因为静态成员函数并不具体作用与某个对象,因此,静态成员函数真实的参数的个数,就是程序中写出的参数个数
(一)本质

(二)应用
1. 不使用this指针
#include<iostream> using namespace std; class A { private: int i; public: void set(int x) { i = x; } int get() { return i; } }; int main() { A a; a.set(9); cout << a.get() << endl; return 0; }
讯享网
2. 使用this指针
讯享网#include<iostream> using namespace std; class A { private: int i; public: void set(int x)//给私有成员变量i赋值 { this->i = x;//this指针指向的是当前对象(所谓当前对象就是,谁此时调用set函数,谁就是当前对象) cout << "this指针保存的内存地址为:" << this << endl; } int get() { return i; } }; int main() { A a; a.set(9);//对象a调用set()函数给自己的成员变量i赋值 cout << "对象a所在的内存地址为:" << &a << endl; cout << "对象a所保存的值为:" << a.get() << endl; cout << endl; A b; b.set(999); cout << "对象b所在内存地址为:" << &b << endl; cout << "对象b所保存的地址为:" << b.get() << endl; }

3. 两者代码对比

三、代码举例
1. 举例1
#include<iostream> using namespace std; class Box { private: double length;//长 double breadth;//宽 double height;//高 public: Box(double l = 2.0, double b = 2.0, double h =2.0) { cout << "Constructor called" << endl; length = l; breadth = b; height = h; } double Volume()//体积 { return length * breadth * height; } int compare(Box box)//比较 { return this->Volume() > box.Volume(); } }; int main() { Box Box1(3.3, 1.2, 1.5); Box Box2(2.5, 6.0, 2.0); if (Box1.compare(Box2))//Box1调用的成员函数compare,所以this指针指向的是Box1 { cout << "Box1 is bigger than Box2!" << endl; } else { cout << "Box1 is smaller or equal than Box2!" << endl; } return 0; }

2. 举例2
讯享网代码举例2: #include<iostream> using namespace std; class complex { public: double real,imag; void print() { cout<<real<<","<<imag; } complex(double r,double i):real(r),imag(i)//初始化列表,complex接收传进来的两个数r和i, //将r传给real,将i传给img { ; } complex addone() { this->real++;//等价于real++ this->print();//等价于print return *this;//this指针指向了调用addone()函数的对象 } }; int main() { complex c1(1,1); complex c2(0,0); c2=c1.addone();//c1.anddone会调用addone函数,this指向addone()函数所作用的对象c1, //导致c1的real加1,也就变成了2,然后this指向的print()函数所作用的对象c1,打印c1的real=2,imag=1 return 0; }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/66923.html