面向对象的特点
抽象 封装 继承 多态
类的定义
类的两种定义方式:
1、声明和定义全部放在类体中,需要注意:成员函数如果在类中定义,编译器可能会将其当成内联函数处理
class TestList
{
public:
int *base;
size_t capecity;
size_t size;
public:
void fun()
{
cout << "this is TestList::fun()" << endl;
}
};
int main()
{
TestList mylist;
}
例如注册一个商店购买系统,通过公有属性来修改私有属性的数据
如下修改商品名(name),商品数量(count),商品单价(price)
class CGoods
{
public:
void RegisterGoods(char *n, int c, float p)
{
strcpy(name, n);
count = c;
price = p;
}
private:
char name[20];
int count;
float price;
};
int main()
{
CGoods c1;
c1.RegisterGoods("C++", 10, 40);
return 0;
}
2、声明放在.h文件中,类的定义放在.cpp文件中
class CGoods
{
public:
void RegisterGoods(char *n, int c, float p)
private:
char name[20];
int count;
float price;
};
void CGoods::RegisterGoods(char *n, int c, float p)
{
strcpy(name, n);
count = c;
price = p;
}
int main()
{
CGoods c1;
c1.RegisterGoods("C++", 10, 40);
return 0;
}
访问限定符
C++实现封装的方式:用类将对象的属性和方法结合在一起,让对象更加完善,通过访问权限选择性将接口提供给外部的用户使用
访问限定符:
public:公有
protected:保护
private:私有
1、public修饰的成员在类外可以直接被访问
2、protected和private修饰的成员在雷瓦不能直接被访问
3、访问权限作用域从访问限定符出现的位置开始直到下一个访问限定符出现
4、class的默认访问权限为private,struct为public
面试题:C++中struct和class的区别是什么?
答:C++需要兼容C语言,使用C++中struct可以当成结构体去使用。另外C++中struct还可以用来定义类。和class定义类是一样的,
区别是struct的成员默认访问方式为public,class中成员的默认访问方式为private
类的作用域
类定义了一个新的作用域,类的所有成员都在类的作用域中。在类外定义成员,需要用::作用域解析符指明成员属于哪个类域
在类的创建第二种方式中有提到。
类的大小计算
class CGoods
{
public:
void RegisterGoods(char *n, int c, float p)
{
strcpy(name, n);
count = c;
price = p;
}
private:
char name[20];
int count;
float price;
};
int main()
{
CGoods c1;
cout << "CGoods = " << sizeof(CGoods) << endl;
cout << "c1 = " << sizeof(c1) << endl;
return 0;
}
此处类的大小为20+4+4=28字节,实例化出的对象的大小也为28字节
不计算方法的大小,只计算类中成员变量的大小
且成员变量的大小分开保存,共用一个方法
this指针
多实例化几个对象,发现计算机很精准的找到了需要赋值的成员并给他赋值
在我们的视角看来很简单,通过"."就能找到想要赋值的对象,但从计算机的角度呢?
1 #include <iostream>
2 #include <string.h>
3 using namespace std;
4
5 class CGoods
6 {
7 public:
8 void SetCount(int c)
9 {
10 count = c;
11 }
12 int GetCount()
13 {
14 return count;
15 }
16 private:
17 char name[20];
18 int count;
19 float price;
20 };
21
22 int main()
23 {
24 CGoods c1, c2, c3;
25 c1.SetCount(10);
26 c2.SetCount(20);
27 c3.SetCount(30);
28 cout << "count for c1 = " << c1.GetCount() << endl;
29 cout << "count for c2 = " << c2.GetCount() << endl;
30 cout << "count for c3 = " << c3.GetCount() << endl;
31 return 0;
32 }
此时用到了this指针,代表着当前对象的地址
而什么叫当前对象呢?
谁调用了函数,谁就是当前对象
所以代码应该是这样的
5 class CGoods
6 {
7 public:
8 void SetCount(int c)
9 {
10 this->count = c;
11 }
12 int GetCount()
13 {
14 return count;
15 }
16 private:
17 char name[20];
18 int count;
19 float price;
20 };
this指针是隐藏的,不用我们自己去写
在我们写了一个类后,编译器会按顺序来编译
1、先识别类名
2、识别数据成员
3、识别方法并改写
void SetCount(int c) -> void SetCount(CGoods *this, int c)
而在调用方法时,会先传递对象的地址,再传递参数
c1.SetCount(10); -> SetCount(&c1, 10);
this指针的特性
1、this指针的类型:类类型* const
2、只能在“成员函数”的内部使用
3、this指针本质上其实是一个成员函数的形象,是对象调用成员函数时,将对象地址作为实参传递给this形参,所以对象中不存储this指针
4、this指针是成员函数第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传递,不需要用户传递