C++基础学习记录—this指针
1、概念
1、this指针是一个特殊的指针,存储的对象的首地址,成员函数(类内)都隐含一个this指针。
2、类的成员函数(包括构造函数和析构函数)中都有this指针,因此this指针只能在类内部使用。
3、哪个对象调用成员函数,this指针就指向哪个对象,访问哪个对象的属性。虽然不用手写this指针,但是编译器都会使用this指针来调用成员。
#include<iostream>
using namespace std;
class Test{
private:
string name;
public:
//this可以用来区分同名参数和成员属性
Test(string name){
this->name = name;
}
void test_this(){
cout << this << endl;
}
void show(){
//只有对象才能调用成员,非重名情况编译器自动添加this
cout << name << endl;
cout << this->name << endl;
this->test_this();
}
};
int main(){
Test t1("admin");
t1.show();
return 0;
}
2、应用
1、区分同名参数和成员属性
可以用this指针来区分同名参数和成员属性
2、类中成员的调用都是依赖于this指针的
类中成员的调用都是依赖于this指针的,默认情况下由编译器自动添加
3、链式调用
当返回值是对象引用时,可以返回*this,此函数支持链式调用。
支持链式调用的成员函数的特点:
1、返回值类型是当前类的引用
2、return后面是 *this
#include <iostream>
using namespace std;
class Test{
private:
int num;
public:
Test(int num)//1、可以用this指针来区分同名参数和成员属性
{
this->num=num;
}
//num 读接口
int get_num()
{
//2、类中成员的调用都是依赖于this指针的,默认情况下由编译器自动添加
return this->num;//就是return num
}
//num进行add操作 3、链式调用
//当返回值类型时对象引用时,可以返回*this,此函数支持链式调用
Test& add(int n)
{
num += n;
return *this;
}
};
int main()
{
Test t1(2);
cout << t1.get_num() <<endl;//2
// t1.add(3);
// cout << t1.get_num() <<endl;
// t1.add(4);
// cout << t1.get_num() <<endl;
// t1.add(100);
// cout << t1.get_num() <<endl;
//链式调用 可以对上述代码进行简写
cout << t1.add(3).add(4).add(100).get_num() << endl;
return 0;
}