this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。
所谓当前对象,是指正在使用的对象。例如对于stu.show();,stu 就是当前对象,this 就指向 stu。
源程序
main.cpp
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
/**this 是 C++ 中的一个关键字,也是一个 const 指针,它指向当前对象,通过它可以访问当前对象的所有成员。
所谓当前对象,是指正在使用的对象。例如对于stu.show();,stu 就是当前对象,this 就指向 stu。
this 虽然用在类的内部,但是只有在对象被创建以后才会给 this 赋值,
并且这个赋值的过程是编译器自动完成的,不需要用户干预,用户也不能显式地给 this 赋值。
*/
int main()
{
Student* ptr_student = new Student;
ptr_student->set_name("改改笨笨");
ptr_student->set_age(28);
ptr_student->set_score(99.8);
ptr_student->show();
/**本例中,this 的值和 ptr_student 的值是相同的。
我们不妨来证明一下,给 Student 类添加一个成员函数printThis(),专门用来输出 this 的值
*/
cout << "ptr_student的值是:" << ptr_student << endl;
cout << "this的值是:" ;
ptr_student->printThis();
cout << "************************************\n";
Student* ptr_student2 = new Student;
cout << "ptr_student2的值是:" << ptr_student << endl;
cout << "this的值是:" ;
ptr_student2->printThis();
cout << "************************************\n";
delete ptr_student;
delete ptr_student2;
return 0;
}
include\Student.h
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student();
virtual ~Student();
void set_name(string);
void set_age(int);
void set_score(float);
void show();
void printThis();
protected:
private:
string name;
int age;
float score;
};
#endif // STUDENT_H
src\Student.cpp
#include "Student.h"
Student::Student()
{
//ctor
cout << "我是默认构造函数" << endl;
}
Student::~Student()
{
//dtor
cout << "空间释放了" << endl;
}
void Student::set_name(string Name)
{
this->name = Name;
}
void Student::set_age(int Age)
{
this->age = Age;
}
void Student::set_score(float Score)
{
this->score = Score;
}
void Student::show()
{
cout << this->name << "的年龄是:" << this->age <<", 成绩是:" << this->score << "分" << endl;
}
void Student::printThis()//用来输出 this 的值
{
cout << this << endl;
}