一维数组封装
- myArray.h
1 #pragma once 2 #include <iostream> 3 #include <initializer_list> 4 using namespace std; 5 6 class myArray 7 { 8 public: 9 int *p;//地址 10 int n;//长度 11 public: 12 //根据{}初始化 13 myArray(initializer_list<int> list); 14 ~myArray(); 15 //显示数据 16 void show(); 17 //从大到小排序 18 void sort(); 19 void operator +(myArray &my); 20 };
- myArray.cpp
1 #include "myArray.h" 2 3 myArray::myArray(initializer_list<int> list) 4 { 5 this->n = list.size();//开辟内存 6 this->p = new int[this->n]; 7 int id = 0; 8 for (auto i : list) 9 { 10 this->p[id++] = i; 11 } 12 } 13 14 15 myArray::~myArray() 16 { 17 } 18 19 void myArray::show() 20 { 21 for (int i = 0; i < this->n; i++) 22 { 23 cout << p[i] << endl; 24 } 25 } 26 27 void myArray::sort() 28 { 29 for (int i = 0; i < this->n-1; i++) 30 { 31 for (int j = 0; j < this->n - 1 - i; j++) 32 { 33 if (p[j] < p[j + 1]) 34 { 35 int temp = p[j]; 36 p[j] = p[j + 1]; 37 p[j + 1] = temp; 38 } 39 } 40 } 41 } 42 43 void myArray::operator+(myArray &my) 44 { 45 for (int i = 0; i < this->n; i++) 46 { 47 this->p[i] += my.p[i]; 48 } 49 }
- erweiArray.h
1 #pragma once 2 #include <iostream> 3 #include <initializer_list> 4 using namespace std; 5 6 class erweiArray 7 { 8 public: 9 int **pp;//地址 10 int *p; 11 int n;//长度 12 public: 13 erweiArray(); 14 ~erweiArray(); 15 //根据{}初始化 16 erweiArray(initializer_list<initializer_list<int>> list); 17 //显示数据 18 void show(); 19 };
- erweiArray.cpp
1 #include "erweiArray.h" 2 3 4 5 erweiArray::erweiArray() 6 { 7 } 8 9 10 erweiArray::~erweiArray() 11 { 12 //析构函数 13 for (int i = 0; i < this->n; i++) 14 { 15 delete[] this->pp[i]; 16 } 17 delete this->pp; 18 delete this->p; 19 } 20 21 erweiArray::erweiArray(initializer_list<initializer_list<int>> list) 22 { 23 //开辟指针数组 24 this->n = list.size(); 25 this->p = new int[this->n];//记录每行几个 26 this->pp = new int*[this->n];//记录一共有多少行 27 28 //下标 29 int id0 = 0; 30 //循环赋值 31 for (auto i : list) 32 { 33 this->pp[id0] = new int[i.size()];//再次分配 34 p[id0] = i.size(); 35 int id1 = 0; 36 for (auto j : i) 37 { 38 pp[id0][id1] = j; 39 id1++; 40 } 41 id0++; 42 } 43 } 44 45 void erweiArray::show() 46 { 47 for (int i = 0; i < this->n; i++) 48 { 49 for (int j = 0; j < this->p[i]; j++) 50 { 51 cout << this->pp[i][j]; 52 } 53 cout << endl; 54 } 55 }
- 测试函数
1 #include <iostream> 2 #include "myArray.h" 3 #include "erweiArray.h" 4 using namespace std; 5 6 void main() 7 { 8 /*myArray *p = new myArray{ 1,2,3,4,5 };*/ 9 /*p->sort(); 10 p->show();*/ 11 /*myArray my{ 1,1,1,1,1 }; 12 my + (*p); 13 my.show();*/ 14 15 erweiArray my1{ {1,2,3},{4,5,6},{7,8,9} }; 16 my1.show(); 17 cin.get(); 18 }