Questions and codes
The following program, Because there are data members of the pointer type, you need a constructor that can complete the deep copy. Please supplement the full constructor and destructor (others do not need to move). Where the constructor completes the following three tasks:
(1) assigns a value to each member function, in accordance with the deep copy principle, where arrayaddr should be the first address of a new contiguous space allocated for the preservation of the data;
(2) MyArray ( int *a, int n), to copy the values in an array of a to the space pointed to by the newly assigned arrayaddr;
(3) Getmax () The strategy that the function takes is to return Max directly (so that the work of Max is computed, done by the constructor)
/* Copyright (c) 2015, Yantai University School of Computer * All rights reserved. * File name: Test.cpp * Author: Simbin * Completion Date: April 12, 2015 * Version number: v1.0 */#include <iostream>using namespace Std;class Myarra Y{private:int *arrayaddr;//Save the first address of an array with len integer elements int len; Record the length of the dynamic array int max; The maximum value in the dynamic array (not the data member that must be in the dynamic array) public:myarray (int *a, int n); ~myarray (); int getValue (int i); Gets the value of the element labeled I in the array int getlen (); Returns the array length int getmax (); Returns the maximum value in the array}; Myarray::myarray (int *a,int n) {arrayaddr=new int[n]; Len=n; int i; max=0; int *p; P=a; for (i=0;i<n;i++) {arrayaddr=a; if (*arrayaddr>max) max=*arrayaddr; a++; } arrayaddr=p;} Myarray::~myarray () {delete arrayaddr;} int myarray::getvalue (int i) {//Gets the value of the element labeled I in the array return arrayaddr[i];} int Myarray::getlen () {//returns the array length return len;} int Myarray::getmax () {//returns the maximum value in the array return max;} int main () {int b[10]= {75, 99, 90, 93, 38, 15, 5, 7, 52, 4}; MyArray R1 (b,10); cout<< "Max:" <<r1.getmax () <<endl; int c[15] = {18,68,10,52,3,19,12,100,56,96,95,97,1,4,93}; MyArray R2 (c,15); int i,s=0; for (i=0; I<r2.getlen (); i++) S+=r2.getvalue (i); cout<< "and for all elements:" <<s<<endl; return 0;}
Operation Result:
Six weeks on-machine practice Project 2--My Array class