C++:从结构体开始理解this指针
#include <iostream>
#include <string>
using namespace std;
class student
{
public :
void Init(string id,string name,int age)
{
id_ = id;
name_ = name;
age_ = age;
}
void print()
{
cout << id_ << endl;
cout << name_ << endl;
cout << age_ << endl;
}
public:
string id_;
string name_;
int age_;
};
int main()
{
student s1, s2;
s1.Init("001", "张三", 18);
s1.print();
s1.Init("002", "李四", 18);
s1.print();
s2.Init("001", "王五", 18);
s2.print();
s2.Init("002", "丽萨", 18);
s2.print();
system("pause");
return 0;
}
对于上面的student类中有Init与print两个成员函数,函数体中没有关于不同对象的区分,那当s1调用Init函数时,该函数是如何知道应该设置s1对象,而不是设置s2对象呢?
我们知道在C++中结构体和类的区别并不是很大,所以我们可以先看看在C语言的结构体中是怎么解决这个问题的。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Windows.h>
struct student
{
char _id[20];
char _name[20];;
int age_;
};
//初始化
void InitStudent(student *s,char *id, char *name, int age)
{
strcpy(s->_id, id);
strcpy(s->_name, name);
s->age_ = age;
}
void PrintStudent(student *s)
{
printf("%s-%s-%d\n", s->_id, s->_name, s->age_);
}
int main()
{
struct student s1, s2;
InitStudent(&s1, "001", "Peter", 18);
PrintStudent(&s1);
InitStudent(&s2, "001", "lisa", 18);
PrintStudent(&s2);
system("pause");
return 0;
}
可以看到在C语言的的结构体中,初始化的时候多传了一个指针,有了这个指针,我们就可以知道要给哪一个结构体当中的变量赋值了,其实在C++中也传了一个指针,只是它被隐藏了,所以我们看不到,这就是this指针,this指针里面存放的就是当前对象的地址(即成员函数执行时,调用该成员函数的对象)。
#include <iostream>
#include <string>
using namespace std;
class student
{
public:
void Init(string id, string name, int age)
{
this->id_ = id;
this->name_ = name;
this->age_ = age;
}
void print()
{
cout << this->id_ << endl;
cout << this->name_ << endl;
cout << this->age_ << endl;
}
public:
string id_;
string name_;
int age_;
};
int main()
{
student s1, s2;
s1.Init("001", "张三", 18);
s1.print();
s1.Init("002", "李四", 18);
s1.print();
s2.Init("001", "王五", 18);
s2.print();
s2.Init("002", "丽萨", 18);
s2.print();
system("pause");
return 0;
}
上面的代码,我们把this指针写出来了,使用之后的结果和之前是一样的;
void Init(string id, string name, int age)
{
this->id_ = id;
this->name_ = name;
this->age_ = age;
}
void print()
{
cout << this->id_ << endl;
cout << this->name_ << endl;
cout << this->age_ << endl;
}
注意:
1.this指针是类类型* const,不能修改
2.this指针只能在“成员函数”内部指用
3.this指针本质上其实是一个成员函数的形参,是对象调用成员函数时,将对象地址作为实参传递给this形参。所以对象中不存储this指针。
4. this指针是成员函数第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递,不需要用户传递