1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
template<class T, int N> class myArray {
public:
myArray( );
explicit myArray( T );
T& operator[]( int n );
T* dataPtr( int n );
int size() const { return N; };
void fill( const T& x );
void printAll() const;
private:
T elem[N] {};
};
template<class T, int N>
myArray<T,N>::myArray()
: myArray{ T{} } {}
template<class T, int N>
myArray<T,N>::myArray(T t) {
for(size_t i{}; i<N; ++i)
elem[i] = t;
}
template<class T, int N>
T& myArray<T,N>::operator[](int n) {
return elem[n];
}
template<class T, int N>
T* myArray<T,N>::dataPtr(int n) {
return &(elem[n]);
}
// fills array with const T& val
template<class T, int N>
void myArray<T,N>::fill(const T& x) {
fill(*this, x); // uses the support function
}
// outputs myArray as a list
template<class T, int N>
void myArray<T,N>::printAll() const {
std::cout << "[";
for (unsigned int i=0; i<N-1; ++i)
std::cout << elem[i] << ", ";
std::cout << elem[N-1] << "]\n";
}
//-------------no class members-----------------------
// fills myArray with const T& val
template<class T, int N>
void fill(myArray<T,N>& r, const T& val) {
for (size_t i{}; i<N; ++i)
r[i] = val;
}
|