this指针使用演示(C++)
this指针指向当前对象,且是已经创建的对象
使用this指针甚至可以让成员函数的参数和成员变量重名
图中高亮部分体现了成员变量与成员函数参数的关系
显然,this指针指向的变量与对象的成员变量相关联
this指针只在类的成员函数内部使用
演示代码如下:
#include <iostream>
using namespace std;
class student
{
private:
string name;
int age;
float score;
public:
student();
student(string name, int age, float score);
void print();
};
student::student()
{
this->name = "";
this->age = 0;
this->score = 0.0;
}
student::student(string name, int age, float score)
{
this->name = name;
this->age = age;
this->score = score;
}
void student::print()
{
cout << "姓名:" << this->name << endl;
cout << "年龄: " << this->age << endl;
cout << "分数: " << this->score << endl;
}
int main()
{
student stu("zzj", 19, 98);
stu.print();
return 0;
}