C++学习笔记 lesson2 类和对象
来源:互联网 发布:租人软件app 编辑:程序博客网 时间:2024/05/23 14:22
可变长数组举例
#include<cstringt.h>//可变长数组// new delete 更改长度 new新空间 , copy旧空间 , delete旧空间// malloc free relloc 分配起来更简单class MyArray{public: MyArray(const size_t len=10)//给初始长度{_index = 0;_len = len;_data = new int[_len];}~MyArray(){if (_data)delete[]_data;}int GetData(const size_t index) const{if (_len > index)return _data[index];return 0;}void SetData(const size_t index, const int num){if (_len > index)_data[index] = num;}unsigned int GetLen() const //有效的长度 返回_index {return _index;}void AddData(const int num) //可以把Add和set合并{if (_index >= _len){_len = _index * 2;int *temp = new int[_len];//每次分配*2的空间memcpy(temp, _data, _index*sizeof(int));delete[]_data;_data = temp; }_data[_index++] = num; // index后++ ,否则无_data[0]}void AddData(const MyArray&data) //增加自身对象{for (unsigned int i = 0; i < data._index; ++i){//const 方法能够被const对象调用, const对象只能调用const方法AddData(data.GetData(i));//不能将“this”指针 每一个对象里面的隐藏属性,每一个对象都有//this 是一个对象的代名词,区分不同的对象//每一个类里面,为了区分每一个对象,会默认包含一个this指针//} }void AddData(const int *data,const unsigned int ) //增加数组,需要长度参数 {for (int i = 0; i < _len; i++){AddData(data[i]);}}//写函数的重载时,会相互调用,节约代码量/*int& Index( const size_t index) {if (index<_len)return _data[index];} 使用引用直接返回,返回index>len的情况不方便表示*/private:int *_data;unsigned int _len; //已经分配的空间unsigned int _index; //已经使用的空间};
0 0
- C++学习笔记 lesson2 类和对象
- C语言学习笔记 lesson2 编程概述
- Java学习笔记--Lesson2(Java面向对象编程)
- C语言提高班学习笔记 lesson2 结构体
- Mybatis框架学习笔记 lesson2
- O-C学习笔记,类和对象
- OBJ-C类和对象学习笔记
- Windows编程学习笔记 lesson2 窗口创建
- CS231n lesson2. Linear classification I 学习笔记
- Objective-C学习笔记2:类、对象和方法
- C++Primer学习笔记------对象和类(1)
- C++Primer学习笔记------对象和类(2)
- iOS学习笔记-Objective-C-类和对象
- 学习笔记-类和对象
- 数据结构算法笔记 lesson2 算法 时间复杂度和空间复杂度
- C语言Lesson2
- XML 自学笔记 Lesson2
- Quartz学习之Lesson2-Quartz的API,Job和Trigger
- C++中int、string等常见类型转换
- ZooKeeper配置和学习笔记
- NIO学习笔记
- Codeforces 471D MUH and Cube Walls【思维+KMP】
- css基础学习---表单学习
- C++学习笔记 lesson2 类和对象
- 卡片布局
- 11期 1月期刊自荐
- 原生js兼容性问题
- androidstudio 导入别人demo报错
- OFDM系统的关键技术及分析
- 报错unrecognized windows sockets error:0:JVM_Bind
- DoubleLockedQueue
- eclipse快捷键