C++ 实例练习-替换原生数组
main.cpp
1 #include <stdio.h> 2 #include "intarray.h" 3 4 int main(int argc, char *argv[]) 5 { 6 int pra = 2; 7 IntArray a(5); 8 a.length(); 9 a.get(pra , 3); 10 return 0; 11 }
IntArray.cpp
1 #include "intarray.h" 2 #include <iostream> 3 using namespace std; 4 IntArray::IntArray(int len){ 5 Pointer_1 = new int[len]; 6 length_1 = len; 7 for(int i = 0; i< len; i++){ 8 Pointer_1[i] = i+1; 9 cout << Pointer_1[i] <<endl; 10 } 11 } 12 13 int IntArray::length(){ 14 cout << "length:" << length_1 <<endl; 15 return length_1; 16 } 17 18 bool IntArray::get(int& pra , int i){ 19 if ((i > length_1)&& ( i < 0 )){ 20 return false; 21 } 22 else { 23 pra = Pointer_1[i]; 24 cout <<" i :" << pra <<endl; 25 } 26 } 27 28 bool IntArray::set(int pra_1, int setPra){ 29 if ((pra_1 > length_1)&& ( pra_1 < 0 )){ 30 return false; 31 } 32 else { 33 Pointer_1[pra_1] = setPra; 34 } 35 for(int i = 0; i< length_1; length_1++) 36 { 37 cout << Pointer_1[i] <<endl; 38 } 39 } 40 41 void IntArray::free() 42 { 43 delete[] Pointer_1; 44 }
IntArray.h
#ifndef INTARRAY_H #define INTARRAY_H class IntArray { public: IntArray(int len); int length(); bool get(int& pra , int i); bool set(int pra_1, int setPra); void free(); private: int * Pointer_1; int length_1; }; #endif // INTARRAY_H