Skip to content

this指针

1.作用

this是一个用来指向当前对象指针,也就是说谁调用这个函数,this就指向哪个对象

  • 每一个对象都能通过 this 指针来访问自己的地址
  • this是一个隐藏的指针,只有成员函数才有 this 指针,它可以用来指向调用对象。
  • 当一个对象的成员函数被调用时,编译器会隐式地传递该对象的地址作为 this 指针
c++
#include<iostream>
using namespace std;

class Person {
public:
	const int age = 18;
	int getAge() {
		return this->age;
	}
};

int main() {
	Person p1;
	cout << p1.getAge() << endl;  // 18
	return 0;
}

2.省略this

理论上来讲,在类的内部,访问当前类中的(非静态)成员的时候,应该都使用this->来访问。

实际上,绝大多数的情况下,this->都是可以省略不写的

c++
class Person {
public:
	const int age = 18;
	int getAge() {
		// return this->age;
        // 等同于
        return age;
	}
};

注意

但是在一个函数内,出现了局部变量和属性同名字的情况,比如构造函数,这种情况下除了使用初始化列表,也可以使用this->初始化值

c++
#include<iostream>
using namespace std;

class Person {
public:
	int age;
	string name;
    
	Person(int age,string name) {
		this->age = age;
		this->name = name;
	}
};

int main() {

	Person p1(18,"xiazhi");
	cout << p1.age << endl;		// 18
	cout << p1.name << endl;	// xiazhi

	return 0;
}

3.函数返回对象本身

在定义成员函数时,若把对象本身返回出去,那我们就可以实现链式调用

c++
class MyNumber {
public:
	int num;
	MyNumber() {
		num = 0;
	}

	MyNumber& add(int num) {
		this->num += num;
		return *this;
	}
};

int main() {

	MyNumber n;
	n.add(10).add(20).add(30);  // 50
    
	cout << n.num << endl;
    
	return 0;
}

因为返回的是对象本身,所以可以继续调用对象身上的方法

以上add()方法相当于如下写法,也就是把当前对象赋值给了一个引用变量,再返回出去

c++
MyNumber& add(int num) {
	this->num += num;
    
	MyNumber& that = *this;
	return that;
}

MIT Licensed