在看this指针之前,我们来想个问题,在定义了类对象之后,他是如何知道该类里面都有些什么的呢?那么假如说我们还没有学习类,对象这些知识,怎么用C语言来模拟实现一个类呢?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<iostream>
using namespace std;
typedef struct Student
{
char name[20];
char gender[3];
int age;
};
void insitle( Student* ps, char*name, char*gender, int age)
{
assert(ps);
assert(name);
assert(gender);
ps->age = age;
strcpy_s(ps->gender, gender);
strcpy_s(ps->name, name);
}
void print( Student* ps)
{
assert(ps);
cout << ps->age << "-" << ps->gender << "-" << ps->name<<endl;
}
int main()
{
struct Student s1;
insitle(&s1, "啦啦", "女", 18);
print(&s1);
typedef struct Student
{
char name[20];
char gender[3];
int age;
};
void insitle( Student* ps, char*name, char*gender, int age)
{
assert(ps);
assert(name);
assert(gender);
ps->age = age;
strcpy_s(ps->gender, gender);
strcpy_s(ps->name, name);
}
void print( Student* ps)
{
assert(ps);
cout << ps->age << "-" << ps->gender << "-" << ps->name<<endl;
}
int main()
{
struct Student s1;
insitle(&s1, "啦啦", "女", 18);
print(&s1);
cout<<sizeof(s1)<<endl;
system("pause");
return 0;
}
system("pause");
return 0;
}
这里的ps是个结构体指针,他能让你之后的定义的对象知道,你的类里面都有些什么,会有一些什么样的操作。
那么他就相当于我们的this指针了.this指针指向的是当前的对象的地址,在编译器编译的时候编译器会把代码修改成如下形势。但是你写的时候是不用给它传this指针的,直接用就好。
结果分析:
首先输出了我们想要的结果,其次我们求了一个对象的大小,可以计算一下,这个大小刚好是我们的成员变量的大小(当然现在还不能叫成员变量),虽有this指针,但不影响所求对象的大小。
为了更能说明问题,我们再来看两个例子,在C++下说明问题
代码:
#include<iostream>
#include<stdlib.h>
using namespace std;
class Date
{
public:
void InitDate(int year,int month,int day)
{
_year = year;
_month = month;
_day = day ;
}
void PrintDate()
{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
protected :
int _year;
int _month;
int _day;
};
class Test1
{};
int main()
{
Date d1,d2,d3;
d1.InitDate(2016,10,9 );
d2.InitDate(2016,11,5);
d1.PrintDate ( );
d2.PrintDate ( );
cout<<sizeof(Date)<< endl; //测试类的大小
cout<<sizeof(Test1 )<< endl; //测试空类的大小
system("pause");
return 0;
}
{
public:
void InitDate(int year,int month,int day)
{
_year = year;
_month = month;
_day = day ;
}
void PrintDate()
{
cout<<_year<<"-"<<_month<<"-"<<_day<<endl;
}
protected :
int _year;
int _month;
int _day;
};
class Test1
{};
int main()
{
Date d1,d2,d3;
d1.InitDate(2016,10,9 );
d2.InitDate(2016,11,5);
d1.PrintDate ( );
d2.PrintDate ( );
cout<<sizeof(Date)<< endl; //测试类的大小
cout<<sizeof(Test1 )<< endl; //测试空类的大小
system("pause");
return 0;
}
运行结果:
一起来总结一下:
1.this指针的类型是类类型,是*const;
2.this指针并不是对象本身的一部分,所以并不影响sizeof的值
3.this指针是类成员函数的第一默认隐含函数,编译器自动维护传送类编写者不能显示传递。
4.this指针的作用域在类成员函数的内部。