前言
本文主要描述this指针和空指针的定义,以及他们在程序中的作用。
一、this指针是什么?
1.定义:this指针在类的成员函数中指向调用该函数的对象
2.实际上,在非静态成员函数中,系统默认在第一个成员变量上隐藏了一个this指针,用来指向调用该函数的对象。
class Car
{
public:
int m_price;
void SetPrice(int p)
{
this->m_price = p; // 等价于 m_price = p;
this->PrintPrice();// 等价于 PrintPrice();
}
};
3.它在程序中常用到的地方:
- 当形参和成员变量同名时,可用this指针来区分
class MyClass {
int value;
public:
MyClass(int value) {
this->value = value; // 使用this指针区分成员变量和参数
}
};
- 链式调用
this指针也可以用于返回对象本身,从而实现函数的链式调用,return *this
class Calculator {
int result;
public:
Calculator() {
result = 0;
}
Calculator& add(int value) {
result += value;
return *this; // 返回对象本身,实现链式调用
}
int getResult() {
return result;
}
};
int main() {
Calculator calc;
int sum = calc.add(5).add(10).add(15).getResult(); // 链式调用
cout << "Sum: " << sum << endl;
return 0;
}
二、空指针是什么?
1.空指针的定义:空指针通常用null指针表示,其值为0或nullptr。
2.创建一个空指针,空指针初始化int* ptr = nullptr;
3.在使用指针之前,通常需要检查指针是否为空,以避免对空指针进行操作。这样做可以提高代码健硕性。我们在this指针知道,在非静态成员函数里面是系统默认创建一个this指针,如果没有创建对象,就会报错,我们可以这样设计一个程序
class person {
public:
void print02() {
//为了提高程序的健壮性
if (this == NULL) {
return;
}
cout<<"this is print02的age"<<this->age << endl;//这里的age的属性,隐藏着一个this->age
}
int age;
};
总结
1.this指针指向的是调用该函数的对象,主要用在的地方有防止形参和成员属性重名,还有利用 return *this来实现链式调用
2.空指针主要是对指针进行初始化,还有利用空指针来使代码更加健硕