Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C++ 2. Suppose you are defining a class named Array to represent lists of up to

ID: 3738825 • Letter: C

Question

C++

2. Suppose you are defining a class named Array to represent lists of up to 100 type double values. You want to allow input of such a list from a file that con- tains first the list length and then the list values. You also want to be able to out- put the list (filled values only) and to create a new Array object and initialize its value to a copy of another Array, copying only the filled elements and the size Here is the declaration of such a class. Write out implementations of the copy constructor and of operators >>and

Explanation / Answer

const int MAX_SIZE = 100;

class Array {
public:
   Array() {
      
   }
   Array(const Array &);
private:
   int size;
   double list[MAX_SIZE];
  
friend istream& operator >> (istream&, Array &);
friend ostream& operator << (ostream&, const Array &);
};

Array::Array(const Array &a) {
   size = a.size;
   for(int i = 0; i < size; ++i) {
       list[i] = a.list[i];
   }
}

istream& operator >> (istream& in, Array &a) {
   cin >> a.size;
   for(int i = 0; i < a.size; ++i) {
       cin >> a.list[i];
   }
   return in;
}

ostream& operator << (ostream& out, const Array &a) {
   for(int i = 0; i < a.size; ++i) {
       out << a.list[i] << " ";
   }
   return out;
}