可变长数组类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| #include<iostream> #include<string.h> using namespace std; class MyArray // 可变长数组类 { private: int m_size; // 数组有效元素的个数 int* m_ptr; // 指向动态分配的数组 int len;//动态数组的空间大小,即最多能有多少个元素
public: MyArray(int s = 0) // 1. 构造函数,s代表数组元素的个数 { if (s == 0){ m_size = 0; m_ptr = NULL; len = 0; } else { m_size = 0; m_ptr = new int[s](); memset(m_ptr, 0, s); len = s; }
} MyArray(MyArray &a){ if (this != &a){ if (a.m_ptr != NULL){ m_size = a.m_size; m_ptr = new int[m_size]; } else { m_size = 0; m_ptr = NULL; }
}
}
~MyArray(){ if (m_ptr){ delete[]m_ptr; m_size = 0; m_ptr = NULL; cout << "调用了析构函数\n"; }
} MyArray & operator=(const MyArray & a)// 4. 重载赋值=运算符函数,用于数组对象间的赋值 { if (this != &a){//this是当前对象的指针(地址) ,a 是对象 所以&a if(a.m_ptr==NULL){ m_size=0; len=0; m_ptr=NULL; } else delete []m_ptr;//删除原有 m_size = a.m_size; len = a.len; m_ptr = new int[a.len]; memcpy(m_ptr, a.m_ptr, a.len*sizeof(int));//最后一个参数不是指个数,是内存大小,故要乘以每个数的大小 } return *this;
} int & operator[](int i) // 5. 重载[]运算符函数,用于获取数组下标对于的值 { if(i>=1) return m_ptr[i-1]; return m_ptr[0]; } void push_back(int v) // 6. 加入一个元素到数组的末尾 {
if (len <= m_size){ if (len == 0){ len += 1; }
int *p = new int[len * 2];
memcpy(p, m_ptr, m_size*sizeof(int)); delete[]m_ptr; m_ptr = p; len = len * 2; cout << "发生了拷贝\n"; } m_ptr[m_size] = v; m_size++;
} int length() // 7. 获取数组的长度 { return m_size; } }; int main(void){ MyArray myarry(0); int n; while (cin >> n) { if (n == -1){ break; } else { myarry.push_back(n); } } MyArray my2; my2 = myarry;//调用了重载的“=” cout<<"调用:my2 = myarry的重载后的my2的元素个数"<<my2.length()<<endl; cout<<"需要查找的值的位置:"; cin>>n; cout << "第"<<n<<"个值=" << myarry[n] << endl; cout << "输入了" << myarry.length() << "个整数\n"; getchar(); return 0; }
|