this 指针是一个特殊的指针,它指向当前对象的实例。
每一个对象都能通过 this 指针来访问自己的地址。
this是一个隐藏的指针,可以在类的成员函数中使用,它可以用来指向调用对象。
当一个对象调用成员函数时,编译程序先将对象的地址赋给this指针, 然后调用成员函数。
友元函数没有 this 指针,因为友元不是类的成员,只有成员函数才有 this 指针。
#include <iostream>
class MyClass {
private:
int value;
public:
void setValue(int value) {
// 使用this指针来引用当前对象的成员变量value,并将传入的值赋给它
this->value = value;
// 告诉编译器我们想要访问当前对象的成员变量,而不是函数参数或局部变量
}
void printValue() {
std::cout << "Value: " << this->value << std::endl;
}
};
int main() {
MyClass obj;
obj.setValue(42);
obj.printValue();
return 0;
}
以上代码执行输出结果为:
Value: 42
更多实例:
#include <iostream>
using namespace std;
class Box
{
public:
// 构造函数定义
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"调用构造函数。" << endl;
length = l;
breadth = b;
height = h;
}
double Volume()
{
return length * breadth * height;
}
int compare(Box box)
{
return this->Volume() > box.Volume();
}
private:
double length; // 宽度
double breadth; // 长度
double height; // 高度
};
int main(void)
{
Box Box1(3.3, 1.2, 1.5); // 声明 box1
Box Box2(8.5, 6.0, 2.0); // 声明 box2
if(Box1.compare(Box2))
{
cout << "Box2 的体积比 Box1 小" <<endl;
}
else
{
cout << "Box2 的体积大于或等于 Box1" <<endl;
}
return 0;
}