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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
//Array.h
#ifndef ARRAY_H
#define ARRAY_H
#include <iostream>
using namespace std;
template <class T, int numberelements>
class Array
{
friend ostream & operator<<(ostream &, const Array<T, numberelements> &);
friend istream & operator>>(istream &, Array<T, numberelements> &);
public:
Array(void);
const Array<T, numberelements> & operator=(const Array<T, numberelements>&);
Array<T, numberelements> operator+(const Array<T, numberelements> &) const;
private:
T array[numberelements];
};
#endif
//Array.cpp
#include "Array.h"
#include <iostream>
using namespace std;
template <class T, int numberelements>
ostream & operator<<(ostream &output, const Array<T, numberelements> &arr)
{
for (int i = 0; i < numberelements; i++)
output << arr.array[i] << " ";
return output;
}
template <class T, int numberelements>
istream & operator>>(istream &input, Array<T, numberelements> &arr)
{
for (int i = 0; i < numberelements; i++)
input >> arr.array[i];
}
template <class T, int numberelements>
Array<T, numberelements>::Array(void)
{
for (int i = 0; i < numberelements; i++)
array[i] = 0;
}
template <class T, int numberelements>
const Array<T, numberelements> & Array<T, numberelements>::operator=(const Array<T, numberelements> &right)
{
for (int i = 0; i < numberelements; i++)
array[i] = right.array[i];
return *this;
}
template <class T, int numberelements>
Array<T, numberelements> Array<T, numberelements>::operator+(const Array<T, numberelements> &right) const
{
Array<T, numberelements> temp;
for (int i = 0; i < numberelements; i++)
temp.array[i] = array[i] + right.array[i];
return temp;
}
//testarraytemplate.cpp
#include "Array.h"
#include <iostream>
using namespace std;
int main(void)
{
Array<int, 3> a1, a2, a3;
cout << a1;
cin.get();
return 0;
}
| |