this指针作为一个隐含参数传递给非静态成员函数,用以指向该成员函数所属类所定义的对象。当不同的对象调用同一个类的成员函数代码时,编译器会依据该成员函数的this指针所指向的不同对象来确定应该引用哪个对象的数据成员。
在 C++ 中,每一个对象都能通过 this 指针来访问自己的地址。this 指针是所有成员函数的隐含参数。因此,在成员函数内部,它可以用来指向调用对象。
- #include<iostream>
- #include<string>
- using namespace std;
- class Stu_Info_Mange
- {
- int sno;
- string sname;
- int age;
- int grade;
- public:
- Stu_Info_Mange(int s=0,string n="",int a=0,int g=0)
- {
- sno=s;
- sname=n;
- age=a;
- grade=g;
- }
- void Setsname(int sn) //使用this指针进行赋值
- {
- this->sname=sn;
- }
- int Setage(int a)
- {
- this->age=a;
- return (*this).age; //使用this指针返回该对象的年龄
- }
- void print()
- {
- cout<<"the sname is "<<this->sname<<endl; //显式this指针通过箭头操作符访问
- cout<<"the sno is "<<sno<<endl;//隐式使用this指针打印
- cout<<"the age is "<<(*this).age<<endl;//显式使用this指针通过远点操作符
- cout<<"the grade is "<<this->grade<<endl<<endl;
- }
- };
- int main()
- {
- Stu_Info_Mange sim1(761,"张三",19,3);
- sim1.print(); //输出信息
- sim1.Setage(12); //使用this指针修改年龄
- sim1.print(); //再次输出
- return 0;
- }
#include <iostream> using namespace std; class Box { public: // 构造函数定义 Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << 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; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 if(Box1.compare(Box2)) { cout << "Box2 is smaller than Box1" <<endl; } else { cout << "Box2 is equal to or larger than Box1" <<endl; } return 0; }
当上面的代码被编译和执行时,它会产生下列结果:
Constructor called. Constructor called. Box2 is equal to or larger than Box1