this指针
大家好,这篇文章将为大家介绍C++中的this指针,包括其定义、用法、案例和注意事项等方面的内容。
一、 什么是this指针?
在C++中,this是一个关键字,用于表示当前对象的指针。在成员函数内部,this指针总是指向调用该函数的对象。这样就可以在成员函数中访问对象的成员变量和成员函数。
二、this指针的定义
this指针是一个指向调用当前成员函数的对象的指针,它指向的是类的非静态成员。在成员函数中,可以使用this指针来访问成员变量和成员函数。
三、this指针的用法
- 访问成员变量
在成员函数中,如果成员变量和参数同名,就无法直接访问到成员变量,此时可以使用this指针来显式地访问成员变量。例如:
class Worker {
private:
string name;
int age;
public:
void setName(string name) {
this->name = name;
}
void setAge(int age) {
this->age = age;
}
};
- 访问成员函数
在成员函数内部,可以通过this指针调用对象的其他成员函数。例如:
class Student {
public:
void hello() {
cout << "Hello, my name is " << this->name << endl;
}
void setName(string name) {
this->name = name;
}
private:
string name;
};
- 返回指向对象的指针
在成员函数中,如果想要返回指向对象的指针,就可以使用this指针。例如:
class Car {
public:
Car* newInstance() {
return this;
}
void run() {
cout << "The car is running." << endl;
}
};
- 防止同名变量的误操作
在成员函数中,如果函数参数和成员变量同名,就容易产生误操作。此时可以使用this指针来区分它们,防止误操作。
四、this指针的案例
demo 1
一个使用this指针的案例是在类的构造函数和析构函数中,this指针用于需要在一个对象的生命周期内进行处理的工作。
class Rectangle {
public:
Rectangle(double width, double height) {
this->width = width;
this->height = height;
cout << "Constructing a rectangle object." << endl;
numberOfObjects++;
}
~Rectangle() {
cout << "Destructing a rectangle object." << endl;
numberOfObjects--;
}
double getWidth() {
return this->width;
}
double getHeight() {
return this->height;
}
static int getNumberOfObjects() {
return numberOfObjects;
}
private:
double width;
double height;
static int numberOfObjects;
};
this指针在这个例子中用于区分构造函数和成员变量之间的命名冲突。
demo 2
this比较常用的用法
#include <iostream>
using namespace std;
/*非静态成员函数不属于某一对象,同类型的对象会共用一块代码
那么这块代码如何区分是哪一个对象调用自己?
this指针:指向被调用的成员函数所属对象。eg.有p1,p2,p3等对象,谁调用,this指针就指向谁
this指针隐含在每个非静态成员函数内,不需要定义,直接使用
用途:1.当形参和成员变量同名的时候,用this指针区分
2.在类的非静态成员函数中返回对象本身,使用 return *this
*/
class Person
{
public:
Person(int age){
this->age = age;
}
//以引用的形式返回
Person& addPersonAge(Person &p) //person addPersonAge() 以值的形式返回,会创建一个新的对象,只会返回p3,无论链式多少,结果只会是20
{
this->age = this->age + p.age;
return *this;
}
int age;
};
//1.区分变量名
void test01()
{
Person p1(18);
cout << "年龄为:" << p1.age << endl;
}
//2.返回对象本身*this
void test02()
{
Person p2(5);
Person p3(10);
p3.addPersonAge(p2);
p3.addPersonAge(p2).addPersonAge(p2).addPersonAge(p2);
cout << "年龄为:" << p3.age << endl; // 结果30
}
int main()
{
test01();
test02();
return 0;
}
五、注意事项
-
在静态成员函数中不能使用this指针。因为静态成员函数没有this指针,它们仅能访问静态数据成员和静态成员函数。
-
this指针不需要显示地定义,编译器会自动添加。
-
空指针访问成员变量,提前判断,保证程序健壮。
#include<iostream>
#include<>
using namespace std;
class Person
{
public:
void showName()
{
printf("这是类的名字\n");
}
void showAge()
{
if(this == NULL)
{
return;
}
printf("age=%d\n",mAge); //不加上判断,会报错
//相当于printf("age=%d\n",this->mAge); 空的对象访问里面的属性?
}
int mAge;
};
void test01()
{
Person *p = NULL;
p->showAge();
p->showName();
}
int main()
{
test01();
return 0;
}
六、总结
在C++中,this指针用于表示当前对象的指针,在成员函数中,可以通过this指针访问成员变量和成员函数。使用this指针可以防止同名变量的误操作,并且可以在类的构造函数和析构函数中使用。在使用时需要注意静态成员函数无法使用this指针,编译器会自动添加this指针,无需手动定义。