I need to write a class Stack using another template class Array for internal storage. This is the class Array, which was provided, so I assume I can't modify it:
#ifndef ARRAY_HH
#define ARRAY_HH
template <class A>
class Array {
public:
Array(int size, A val) : _size(size) {
defval=val;
_arr = new A[_size] ;
for (int i=0; i<_size; i++){
_arr[i]=val;
}
}
Array(const Array& other) : _size(other._size) {
_arr = new A[other._size] ;
for (int i=0; i<other._size; i++){
_arr[i]=other.defval;
}
// Copy elements
for (int i=0 ; i<_size ; i++) {
_arr[i] = other._arr[i] ;
}
}
~Array() {
delete[] _arr ;
}
Array& operator=(const Array& other)
{
if (&other==this) return *this ;
if (_size != other._size) {
resize(other._size) ;
}
for (int j=0; j<_size; j++){
_arr[j]=other.defval;
}
for (int i=0 ; i<_size ; i++) {
_arr[i] = other._arr[i] ;
}
return *this ;
}
A& operator[](int index) {
if (index >_size){
std::cout <<"Beyond range, resizing..." <<std::endl;
resize(index+1);
return _arr[index];
}
else{
return _arr[index] ;
}
}
const A& operator[](int index) const {
return _arr[index] ;
}
int size() const { return _size ; }
void resize(int newSize) {
// Allocate new array
A* newArr = new A[newSize] ;
// Copy elements
for (int i=0 ; i<_size ; i++) {
newArr[i] = _arr[i] ;
}
for (int j=_size; j<newSize; j++) {
newArr[j] = defval;
}
// Delete old array and install new one
delete[] _arr ;
_size = newSize ;
_arr = newArr ;
}
private:
int _size ;
A* _arr ;
A defval;
} ;
#endif
Whereas this is the incomplete class Stack:
#ifndef STACK_H
#define STACK_H
#include <iostream>
#include "Array.hh"
class Stack {
// Implementation
private:
int count;
// Interface
public:
Array <double> s;
Stack(){
count=0;
};
int nitems() { return count ; }
bool full() { return (count==s.size()) ; }
bool empty() { return (count==0) ; }
void push(double);
void inspect();
double pop();
};
#endif
I have a problem with the Stack()
constructor, since it returns an error that says:
no default constructor exists for class "Array<double>"
I have tried to pass in arguments, like (int size, double val)
but that does not seem the problem. Moreover, I don't know how to initialize the Array <double> s
with the desired buffer length.