类与对象(1)

  论坛元老 | 2024-7-15 14:59:29 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1801|帖子 1801|积分 5403

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
1.类的界说

(1)类界说格式

      • class为界说类的关键字,Stack为类的名字,{}中为类的主体,注意   类界说结束时后面分号不能省略   。类体中内容称为类的成员:   类中的变量称为类的属性或成员变量; 类中的函数称为类的方法或者成员函数。      
  1. #include<iostream>
  2. #include<assert.h>
  3. using namespace std;
  4. class Stack
  5. {
  6. public:
  7.         // 成员函数
  8.         void Init(int n = 4)
  9.         {
  10.                 array = (int*)malloc(sizeof(int) * n);
  11.                 if (nullptr == array)
  12.                 {
  13.                         perror("malloc申请空间失败");
  14.                         return;
  15.                 }
  16.                 capacity = n;
  17.                 top = 0;
  18.         }
  19.         void Push(int x)
  20.         {
  21.                 // ...扩容
  22.                 array[top++] = x;
  23.         }
  24.         int Top()
  25.         {
  26.                 assert(top > 0);
  27.                 return array[top - 1];
  28.         }
  29.         void Destroy()
  30.         {
  31.                 free(array);
  32.                 array = nullptr;
  33.                 top = capacity = 0;
  34.         }
  35. private:
  36.         // 成员变量
  37.         int* array;
  38.         size_t capacity;
  39.         size_t top;
  40. }; // 分号不能省略
  41. int main()
  42. {
  43.         Stack st;
  44.         st.Init();
  45.         st.Push(1);
  46.         st.Push(2);
  47.         cout << st.Top() << endl;
  48.         st.Destroy();
  49.         return 0;
  50. }
复制代码
        为了区分成员变量,一般风俗上   成员变量会加一个特殊标识   ,如成员变量前面或者后面加_ 或者 m开头   ,注意C++中这个并不是强制的,只是一些惯例,详细看公司的要求。    
  1. class Date
  2. {
  3. public:
  4.         void Init(int year, int month, int day)
  5.         {
  6.                 _year = year;
  7.                 _month = month;
  8.                 _day = day;
  9.         }
  10. private:
  11.         // 为了区分成员变量,⼀般习惯上成员变量
  12.         // 会加⼀个特殊标识,如_ 或者 m开头
  13.         int _year; // year_ / m_year
  14.         int _month;
  15.         int _day;
  16. };
  17. int main()
  18. {
  19.         Date d;
  20.         d.Init(2024, 3, 31);
  21.         return 0;
  22. }
复制代码
         C++中struct也可以界说类,   C++兼容C中struct的用法,同时struct升级成了类   ,明显的变化是struct中可以界说函数   ,一般环境下我们照旧推荐用class界说类。    
  1. #include<iostream>
  2. using namespace std;
  3. // C++升级struct升级成了类
  4. // 1、类⾥⾯可以定义函数
  5. // 2、struct名称就可以代表类型
  6. // C++兼容C中struct的⽤法
  7. typedef struct ListNodeC
  8. {
  9.         struct ListNodeC* next;
  10.         int val;
  11. }LTNode;
  12. // 不再需要typedef,ListNodeCPP就可以代表类型
  13. struct ListNodeCPP
  14. {
  15.         void Init(int x)
  16.         {
  17.                 next = nullptr;
  18.                 val = x;
  19.         }
  20.         ListNodeCPP* next;
  21.         int val;
  22. };
  23. int main()
  24. {
  25.         return 0;
  26. }
复制代码
        界说在类面的成员函数默认为inline   。但是   在类内里声明和界说分离就不是内联函数   了。二者怎么分离在下面类域中讲。      (2)访问限定符

       • C++⼀种实现封装的方式,用类将对象的属性与方法结合在⼀块,让对象更加完满,通过访问权限   选择性的将其接口(函数)提供给外部的用户使用。          • public修饰的成员在类外可以直接被访问;protected和private修饰的成员在类外不能直接被访问,protected和private是一样的,以后继承章节才能体现出他们的区别。          • 访问权限作用域   从该访问限定符出现的位置开始直到下一个访问限定符出现时为止,如果后面没有访问限定符,作用域就到 }即类结束。              class界说成员没有被访问限定符修饰时默认为private,struct默认为public。             一般成员变量都会被限定为private/protected,必要给别人使用的成员函数会放为public。    


(3)类域

      • 类界说了一个新的作用域,类的全部成员都在类的作用域中,   在类体外界说成员时,必要使用 :: 作用域操纵符指明成员属于哪个类域。   (声明与界说分离)       注:类域和定名空间域都只影响名字隔离,不影响生命周期。
  1. #include<iostream>
  2. using namespace std;
  3. class Stack
  4. {
  5. public:
  6.         // 成员函数
  7.          void Init(int n = 4);
  8. private:
  9.         // 成员变量
  10.         int* array;
  11.         size_t capacity;
  12.         size_t top;
  13. };
  14. // 声明和定义分离,需要指定类域
  15. void Stack::Init(int n)
  16. {
  17.         array = (int*)malloc(sizeof(int) * n);
  18.         if (nullptr == array)
  19.         {
  20.                 perror("malloc申请空间失败");
  21.                 return;
  22.         }
  23.         capacity = n;
  24.         top = 0;
  25. }
  26. int main()
  27. {
  28.         Stack st;
  29.         st.Init();
  30.         return 0;
  31. }
复制代码
     • 类域影响的是编译的   查找规则   ,上面程序中Init如果不指定类域Stack,那么编译器就把Init当成全局函数,那么编译时,找不到array等成员的声明/界说在哪里,就会报错。   指定类域Stack,就是知道Init是成员函数,当前域找不到的array等成员,就会到类域中去查找       2.实例化

(1)实例化概念

      • 用类类型在物理内存中创建对象的过程,称为类实例化出对象。          • 类是对象进行一种抽象描述,是一个模型一样的东西,限定了类有哪些成员变量,这些成员变量只是声明,没有分配空间,用类实例化出对象时,才会分配空间。          • 一个类可以实例化出多个对象,实例化出的对象 占用实际的物理空间,存储类成员变量。打个比方:类实例化出对象就像现实中使用建筑设计图建造出房子,类就像是设计图,设计图规划了有多少个房间,房间大小功能等,但是并没有实体的建筑存在,也不能住人,用设计图修建出房子,房子才能住人。同样类就像设计图一样,不能存储数据,实例化出的对象分配物理内存存储数据。    

  1. #include<iostream>
  2. using namespace std;
  3. class Date
  4. {
  5. public:
  6.         void Init(int year, int month, int day)
  7.         {
  8.                 _year = year;
  9.                 _month = month;
  10.                 _day = day;
  11.         }
  12.         void Print()
  13.         {
  14.                 cout << _year << "/" << _month << "/" << _day << endl;
  15.         }
  16. private:
  17.         //声明不是定义
  18.         int _year;
  19.         int _month;
  20.         int _day;
  21. };
  22. int main()
  23. {
  24.         //Date 实例化对象为d1和d2
  25.         Date d1;
  26.     Date d2;
  27.         d1.Init(2024,7,13);
  28.         d1.Print();
  29.     d2.Init(2024,7,14);
  30.         d2.Print();
  31.         return 0;
  32. }
复制代码
(2)对象大小

      分析一下类对象中哪些成员呢?   类实例化出的每个对象,都有独立的数据空间,所以对象中肯定包含成员变量   ,那么成员函数是否包含呢?   起首函数被编译后是一段指令,对象中没办法存储,这些指令存储在一个单独的区域(代码段),那么对象中非要存储的话,只能是成员函数的指针。   再分析一下,对   象中是否有存储指针的必要呢,   Date实例化d1和d2两个对象,d1和d2都有各自独立的成员变量_year/_month/_day存储各自的数据,但是d1和d2的成员函数Init/Print指针却是一样的,存储在对象中就浪费了。如果用Date实例化100个对象,那么成员函数指针就重复存储100次,太浪费了。   这里需   要再额外说一下,   实在函数指针是不必要存储的,函数指针是一个地址,调用函数被编译成汇编指令[call 地址], 实在编译器在编译链接时,就要找到函数的地址,不是在运行时找,只有动态多态是在运行时找,就必要存储函数地址,   这个我们以后会讲解。   

   上面我们分析了对象中只存储成员变量,C++规定类实例化的对象也要符合内存对齐的规则。
  

  1. #include<iostream>
  2. using namespace std;
  3. // 计算⼀下A/B/C实例化的对象是多⼤?
  4. class A
  5. {
  6. public:
  7.         void Print()
  8.         {
  9.                 cout << _ch << endl;
  10.         }
  11. private:
  12.         char _ch;
  13.         int _i;
  14. };
  15. class B
  16. {
  17. public:
  18.         void Print()
  19.         {
  20.                 //...
  21.         }
  22. };
  23. class C
  24. {};
  25. int main()
  26. {
  27.         A a;
  28.         B b;
  29.         C c;
  30.         cout << sizeof(a) << endl;
  31.         cout << sizeof(b) << endl;
  32.         cout << sizeof(c) << endl;
  33.         cout << &a << endl;
  34.         cout << &b << endl;
  35.         cout << &c << endl;
  36.         return 0;
  37. }
复制代码
 

3.this指针

(1)概念及性子

      • Date类中有 Init 与 Print 两个成员函数,函数体中没有关于差别对象的区分,那当d1调用Init和   Print函数时,该函数是如何知道应该访问的是d1对象照旧d2对象呢?那么这里就要看到C++给了一   个隐含的this指针办理这里的题目             编译器编译后,类的成员函数默认都会在形参第一个位置,增加一个当前类类型的指针,叫做this指针。   比如Date类的Init的真实原型为, void Init(Date* const this, int year,   int month, int day)    const在Date*之前修饰的是指向的对象,再Date*之后修饰的是指针本身],   所以this指针是不可以被修改的,但this指向的对象可以被修改。            类的成员函数中访问成员变量,本质都是通过this指针访问的   ,如Init函数中给_year赋值, this->_year = year;             C++规定不能在实参和形参的位置显示的写this指针(编译时编译器会处置处罚),但是可以在函数体内显示使用this指针。        • this指针是存在内存哪个区域?
  this实在是一个形参,形参一般存在栈帧里,但部分编译器(如VS)会优化到寄存器里。
  (2)实例

所以对于上面实例化的例子,实质上可以写成: 
  1. #include<iostream>
  2. using namespace std;
  3. class Date
  4. {
  5. public:
  6.         //void Init(Date* const this,int year, int month, int day)
  7.         void Init(int year, int month, int day)
  8.         {
  9.                 this->_year = year;
  10.                 this->_month = month;
  11.                 this->_day = day;
  12.         }
  13.     //void Print(Date* const this)
  14.         void Print()
  15.         {
  16.                 cout << this->_year << "/" << this->_month << "/" << this->_day << endl;
  17.         }
  18. private:
  19.         //声明不是定义
  20.         int _year;
  21.         int _month;
  22.         int _day;
  23. };
  24. int main()
  25. {
  26.         //Date 实例化出对象d1和d2
  27.         Date d1;
  28.         Date d2;
  29.         d1.Init(2024, 7, 13);
  30.         d1.Print();
  31.         d2.Init(2024, 7, 14);
  32.         d2.Print();
  33.         return 0;
  34. }
复制代码
(3)检测

      1.下面程序编译运行结果是(C)        A、编译报错 B、运行瓦解 C、正常运行   
  1. #include<iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6.         void Print()
  7.         {
  8.                 cout << "A::Print()" << endl;
  9.         }
  10. private:
  11.         int _a;
  12. };
  13. int main()
  14. {
  15.         A* p = nullptr;
  16.         p->Print();
  17.         return 0;
  18. }
复制代码
  1.函数调用会转换成汇编指令,P->rint();这一句会被转化成 “call 地址”,[该地址(成员函数的指针)不在P对象内里,在编译时通过函数名就确定了地址]。对象P要调用类域,由于Print是成员函数。
  2.调用函数要通报this指针(参数),从前C是lea 取地址,现在不必要取地址,由于P就是对象的地址,所以底层的汇编指令就是“mov ecx P”把p的值 mov 给 ecx ,ecx相称于存储的是this指针,再去“call 地址”。
  3.进入到成员函数Print的内部,此时this是空指针,我们看到在Print函数内里,this指针并没有被解引用,所以不会报错。(空指针不会出现编译报错)
       1.下面程序编译运行结果是(B)        A、编译报错 B、运行瓦解 C、正常运行   
  1. #include<iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6.         void Print()
  7.         {
  8.                 cout << "A::Print()" << endl;
  9.                 cout << _a << endl;
  10.         }
  11. private:
  12.         int _a;
  13. };
  14. int main()
  15. {
  16.         A* p = nullptr;
  17.         p->Print();
  18.         return 0;
  19. }
复制代码
  前两步与上面的解释类似,但在第三步,进入到成员函数的内部之后对空指针进行解引用(this->_a),导致程序运行瓦解。
  4.C++和C语言实现Stack对比

   面向对象三大特性:封装、继承、多态,下面的对比我们可以开端了解一下封装。  通过下面两份代码对比,我们发现C++实现Stack形态上照旧发生了挺多的变化,底层和逻辑上没啥变化。         • C++中数据和函数都放到了类内里,通过访问限定符进行了限定,不能再随意通过对象直接修改数   据,这是C++封装的一种体现,这个是最重要的变化。这里的封装的本质是一种更严格规范的管   理,克制出现乱访问修改的题目。当然封装不仅仅是这样的,我们后面还必要不停的去学习。          • C++中有一些相对方便的语法,比如Init给的缺省参数会方便很多,成员函数每次不必要传对象地   址,由于this指针隐含的通报了,方便了很多,使用类型不再必要typedef用类名就很方便       • 在我们这个C++入门阶段实现的Stack看起来变了很多,但是实质上变化不大。等着我们后面看STL中的用适配器实现的Stack,各人再感受C++的魅力。
  1. //C语言实现栈
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #include<stdbool.h>
  5. #include<assert.h>
  6. typedef int STDataType;
  7. typedef struct Stack
  8. {
  9.         STDataType* a;
  10.         int top;
  11.         int capacity;
  12. }ST;
  13. void STInit(ST* ps)
  14. {
  15.         assert(ps);
  16.         ps->a = NULL;
  17.         ps->top = 0;
  18.         ps->capacity = 0;
  19. }
  20. void STDestroy(ST* ps)
  21. {
  22.         assert(ps);
  23.         free(ps->a);
  24.         ps->a = NULL;
  25.         ps->top = ps->capacity = 0;
  26. }
  27. void STPush(ST* ps, STDataType x)
  28. {
  29.         assert(ps);
  30.         // 满了, 扩容
  31.         if (ps->top == ps->capacity)
  32.         {
  33.                 int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
  34.                 STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity *
  35.                         sizeof(STDataType));
  36.                 if (tmp == NULL)
  37.                 {
  38.                         perror("realloc fail");
  39.                         return;
  40.                 }
  41.                 ps->a = tmp;
  42.                 ps->capacity = newcapacity;
  43.         }
  44.         ps->a[ps->top] = x;
  45.         ps->top++;
  46. }
  47. bool STEmpty(ST* ps)
  48. {
  49.         assert(ps);
  50.         return ps->top == 0;
  51. }
  52. void STPop(ST* ps)
  53. {
  54.         assert(ps);
  55.         assert(!STEmpty(ps));
  56.         ps->top--;
  57. }
  58. STDataType STTop(ST* ps)
  59. {
  60.         assert(ps);
  61.         assert(!STEmpty(ps));
  62.         return ps->a[ps->top - 1];//直接访问获取栈顶元素,可以,但不规范
  63. }
  64. int STSize(ST* ps)
  65. {
  66.         assert(ps);
  67.         return ps->top;
  68. }
  69. int main()
  70. {
  71.         ST s;
  72.         STInit(&s);
  73.         STPush(&s, 1);
  74.         STPush(&s, 2);
  75.         STPush(&s, 3);
  76.         STPush(&s, 4);
  77.         while (!STEmpty(&s))
  78.         {
  79.                 printf("%d\n", STTop(&s));
  80.                 STPop(&s);
  81.         }
  82.         STDestroy(&s);
  83.         return 0;
  84. }
复制代码
  1. //C++实现栈
  2. #include<iostream>
  3. using namespace std;
  4. typedef int STDataType;
  5. class Stack
  6. {
  7. public:
  8.         // 成员函数
  9.         void Init(int n = 4)
  10.         {
  11.                 _a = (STDataType*)malloc(sizeof(STDataType) * n);
  12.                 if (nullptr == _a)
  13.                 {
  14.                         perror("malloc申请空间失败");
  15.                         return;
  16.                 }
  17.                 _capacity = n;
  18.                 _top = 0;
  19.         }
  20.         void Push(STDataType x)
  21.         {
  22.                 if (_top == _capacity)
  23.                 {
  24.                         int newcapacity = _capacity * 2;
  25.                         STDataType* tmp = (STDataType*)realloc(_a, newcapacity *
  26.                                 sizeof(STDataType));
  27.                         if (tmp == NULL)
  28.                         {
  29.                                 perror("realloc fail");
  30.                                 return;
  31.                         }
  32.                         _a = tmp;
  33.                         _capacity = newcapacity;
  34.                 }
  35.                 _a[_top++] = x;
  36.         }
  37.         void Pop()
  38.         {
  39.                 assert(_top > 0);
  40.                 --_top;
  41.         }
  42.         bool Empty()
  43.         {
  44.                 return _top == 0;
  45.         }
  46.         int Top()
  47.         {
  48.                 assert(_top > 0);
  49.                 return _a[_top - 1];
  50.         }
  51.         void Destroy()
  52.         {
  53.                 free(_a);
  54.                 _a = nullptr;
  55.                 _top = _capacity = 0;
  56.         }
  57. private:
  58.         // 成员变量——>私有,更规范
  59.         STDataType * _a;
  60.         size_t _capacity;
  61.         size_t _top;
  62. };
  63. int main()
  64. {
  65.         Stack s;
  66.         s.Init();
  67.         s.Push(1);
  68.         s.Push(2);
  69.         s.Push(3);
  70.         s.Push(4);
  71.         while (!s.Empty())
  72.         {
  73.                 printf("%d\n", s.Top());
  74.                 s.Pop();
  75.         }
  76.         s.Destroy();
  77.         return 0;
  78. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表