目录
一、类的对象模型
1.1类的大小计算
类的大小是该类中所有“成员变量”的和(不计算成员函数),还有注意内存对齐。
class A1//含有成员函数
{
public:
void f1()
{
int x = 0;
}
};
class A2//既有成员变量又有成员函数
{
public:
void f2()
{
int y = 0;
}
private:
int _a;
};
class A3//空类
{
//C++规定空类的字节大小为1
};
int main()
{
int a1 = sizeof(A1);
int a2 = sizeof(A2);
int a3 = sizeof(A3);
printf("%d\n", a1);
printf("%d\n", a2);
printf("%d\n", a3);
}
上图中,A1中只有成员函数,类的大小不计算成员函数,所有大小相当于空类,为1。
A2也只计算了_a的字节大小,为4。
1.2类的对象的存储方式
类的对象的存储方式为只保存成员变量,成员函数放在公共的代码段内。
二、this指针
2.1this指针的引出
class Date//日期
{
public:
void Init(int year, int month, int day)//初始化
{
_year = year;
_month = month;
_day = day;
}
void Print()//打印日期
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
int main()
{
Date d1, d2;
d1.Init(2022, 1, 11);
d2.Init(2022, 1, 12);
d1.Print();
d2.Print();
return 0;
}
上述代码中d1调用Init函数时,C++编译器为了区分应该初始化d1还是d2,为每个“非静态的成员函数”设置了一个隐藏的指针参数, 让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有“成员变量”的操作,都是通过该指针去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成。
2.2this指针的特性
1.this指针的类型:类类型*const,在成员函数中,不能给this指针赋值。
2.this指针只能在“成员函数”内使用。
3.this指针本质上是“成员函数”的形参,当对象调用成员函数时,将对象的地址传给this形参,所有对象中不存在this指针。
4.this指针是“成员函数”的第一个形参(隐藏的),虽然不需要用户传递,但用户自己传递的其他参数会排在this指针后面。