YouTube视频链接
C++的this关键字本文是ChernoP41视频的学习笔记。
在C++中有一个关键字this,它可以访问成员函数。this是一个指向当前对象实例的指针,该方法属于这个对象实例。
class Entity
{
public:
int x, y;
Entity(int x, int y)// 成员初始化列表
:x(x), y(y)
{
}
Entity(int x, int y)//参数x赋值给它自己
{
x = x;
y = y;
}
};
我们可以使用成员初始化列表,但如果想在方法内部写,这里的参数和类中的变量名一样,如果直接写x=x,那么只是让参数中的x赋值给它自己,也就是什么都不做。而我们真正想做的是引用这个类的x和y,this关键字可以让我们做到这一点。this关键字是指向当前对象的指针。
class Entity
{
public:
int x, y;
Entity (int x, int y)
{
Entity* e = this;
// // Entity* const e = this;
// this=nullptr; 不能
// // Entity*& const e = this;不能
// Entity* const& e = this;可以
e->x = x;
}
Entity (int x, int y)//简单写法
{
this->x=x; //(*this).x=x;
this->y=y;
}
};
这里的this是一个Entity类型的指针。也可以加上const,这时右边的this不允许把它重新赋值为别的什么。所以不能写成this=nullptr;,也不能把this赋值给这里的引用,实际上需要const的。现在想要赋值x,可以直接用e->x,更简单的写法是this->x=x;。
class Entity
{
public:
int x, y;
Entity(int x, int y)
{
this->x = x;
this->y = y;
}
int GetX() const
{
const Entity* e = this;
//Entity* e = this;错误
}
};
若我们想要写一个返回这些变量之一的函数,在函数后面加上const是非常常见的,因为它不会修改这个类。所以在GetX()函数中就不能将this赋值给一个Entity,而是const Entity。
若我们想在Entity类的内部调用一个类外部的函数 PrintEntity,这个函数将Entity作为参数。我们想传递这个Entity类的当前实例到这个函数,就可以传入this,它会传入我们设置的x和y的当前实例。
void PrintEntity(Entity* e);
class Entity
{
public:
int x, y;
Entity(int x, int y)
{
this->x = x;
this->y = y;
PrintEntity(this);
}
};
void PrintEntity(Entity* e)
{
//print
}
如果我们想把它作为一个常量引用const &,这里要做的就是逆向引用*。通过逆向引用this指针,在非const方法中,我们可以赋值给Entity &。如果在一个const方法中,我们可以将*this赋值给const Entity&,因为这是一个指向当前类的指针。我们还可以调用delete this(不建议)。
class Entity
{
public:
int x, y;
Entity(int x, int y)
{
this->x = x;
this->y = y;
Entity& e = *this;
delete this;//非专业不建议使用
}
int GetX() const
{
const Entity& e = *this;
}
};



