目录
1.面向对象和面向对象初步认识
2.类的引入
class student
{
char _name[10];
int _age;
int _id;
public:
void Init(const char* name, int age, int id)
{
strcpy(_name, name);
_age = age;
_id = id;
}
void print()
{
cout << _name << endl;
cout << _age << endl;
cout << _id << endl;
}
};
int main()
{
class student s1, s2;
s1.Init("张三", 18, 1);
s2.Init("李四",29,2);
s1.print();
s2.print();
return 0;
}
与c语言不同的是c语言中通常用struct 定义结构体而c++中可以使用class来定义
3.类的定义
class className
{
//类体:有成员函数和成员变量组成
};//需要注意后面的分号
定义这样的就放在类体中
4.访问限定符
public:公有被public内包含的都可以被访问到;
private:被private修饰的不可以直接被访问到和protect类似;
访问权限作用域从该访问限定符出现的位置开始直到下一个访问限定符出现为止
如果后面没有限定符作用域就到}类结束
class的默认访问权限为private struct为public因为struct要兼容c。
5.类对象模型
5.1如何计算类大小
问题:我们学到c++中类和c中结构体不同就是c++可以在类中定义函数,那么一个类的大小应该是多少呢?我们也知道c中存在内存对齐,c++中是否一样呢?
typedef class stack
{
public:
void stackInit();
void stackpush(int x);
private:
int*a;
int top;
int capacity;
}SK;
int main()
{
SK s;
s.stackInit();
cout << sizeof(stack) << endl;//这里计算出来都是12个字节。
cout << sizeof(s) << endl;
return 0;
}
结论:以上主函数计算出来都是12个字节,是因为类中的方式函数都放在一个公共区域,是不进入类的大小计算的。类的大小中计算中只包括定义的变量。而且要考虑内存对齐!对齐规则和c一致!
6.this指针
先看下面这段代码
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 s,s1;
s.Init(2022, 2, 26);
s.print();
s1.Init(2022, 2, 27);
s1.print();
return 0;
}
上面s 和s1调用的print函数和Init是同一个函数么?
this的使用
1.调用成员函数时,不能显示传实参给this,
2.定义成员函数时,也不能显示声明形参this。
3.在成员函数内部,我们可以显示使用this。
而且一般情况下this指针是存在栈区的
645

被折叠的 条评论
为什么被折叠?



