在 C++ 中,this 指针是一个特殊的指针,它指向当前对象的实例。
在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。
this是一个隐藏的指针,可以在类的成员函数中使用,它可以用来指向调用对象。
当一个对象的成员函数被调用时,编译器会隐式地传递该对象的地址作为 this 指针。
友元函数没有 this 指针,因为友元不是类的成员,只有成员函数才有 this 指针。
下面的实例有助于更好地理解 this 指针的概念:
#include <iostream> class MyClass { private: int value; public: void setValue(int value) { this->value = value; } void printValue() { std::cout << "Value: " << this->value << std::endl; } }; int main() { MyClass obj; obj.setValue(42); obj.printValue(); return 0; }
以上代码执行输出结果为:
价值: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; }
当上面的代码被编译和执行时,它会产生下列结果:
调用构造函数。 调用构造函数。 Box2 的体积大于或等于 Box1