1.基本介绍
this本身很容易理解:
在C++所有类当中,都将this(关键字)指针设置为当前对象的地址。this本身是指针,*this是变量,类型为当前类的类型。
2.举例
刚开始看到this指针的时候,总会觉得奇怪,怎么会有这种用法。我们需要当前类的变量以及函数的时候,明明可以直接在类的内部直接调用,为啥会多此一举搞出个this呢?
下面有这样一个场景:
想求a,b 值最大的类,并将该类赋值给b。类base当中自带比较函数,如果出现b自身更大的情况,那么就必须要返回类自身。
class base{
public:
base(int value = 0) : m_value(value) {};
base& operator=(const base& other){
if(this != &other)
m_value = other.m_value;
return *this;
}
const base& compare_max(base& other){
if(other.m_value > m_value){
return other;
else
return *this; // 此时如果出现当前值更大的情况,就必须返回自身
}
int m_value;
}
int main(){
base a(1);
base b(2);
// 求a,b 值最大的类,并将该类赋值给max
base max = b.compare_max(a);
}
3.使用
this的使用通常有这么几种情况:
1.this(或*this)作为函数返回值,返回自身。
class base{
public:
base& self(){
return *this;
}
}
2.this(或*this)作为函数参数,需要对自身做进一步处理或者作为输入时。
class base{
public:
void func1(){
func2(*this);
}
void func2(base& b) {}
}
3.自身与同类作比较使用
class base{
public:
bool same(base& other) {
return this == other ? true : false;
}
}
。。to be update