目录
一、关于this指针的一个经典问题
二、this指针的特点
(一)本质
(二)应用
1. 不使用this指针
2. 使用this指针
3. 两者代码对比
三、代码举例
1. 举例1
2. 举例2
当你进入一个房子后,
你可以看见桌子、椅子、地板等,
但是房子你是看不到全貌了。
对于一个类的实例来说,
你可以看到它的成员函数、成员变量,
但是实例本身呢?
this是一个指针,它时时刻刻指向你这个实例本身
#include
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;
}
#include
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;
}
#include
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:
#include
using namespace std;
class complex
{public:double real,imag;void print(){cout<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;
}