Code:
#include <iostream>
using namespace std;
template <class T>
class Array{
private:
T* array;
int size;
public:
Array();
Array(int _size);
Array (Array& rhs);
~Array();
T& operator [] (int offset);
};
template <class T>
Array<T>::Array():size(0), array(NULL) {};
template <class T>
Array<T>::Array(int _size): size(_size){
array=new T[size];
}
template <class T>
Array<T>::Array (Array& rhs){
size=rhs.size;
array=new T[size];
for (int i=0;i<size;i++){
array[i]=rhs[i];
}
}
template <class T>
Array <T>::~Array(){
delete[] array;
}
template <class T>
T& Array<T>::operator [] (int offset){
// T t=array[offset];
// return t;
return array[offset];
}
class Cat{
public:
void meaw (void){
cout<<"Mieaaw\n";
}
void present (void){
cout<<"furrColor: "<<furrColor<<" age: "<<age<<"\n";
}
string furrColor;
int age;
Cat (): furrColor("Black"), age(1){};
};
int main (void){
Array<Cat> array(20)/*[20]*/ ;
for (int i=0;i<20;i++){
array[i].present();
}
return 0;
}
First, this
Code:
$ g++ bar.cpp
bar.cpp: In member function ‘T& Array<T>::operator[](int) [with T = Cat]’:
bar.cpp:70:16: instantiated from here
bar.cpp:45:7: warning: reference to local variable ‘t’ returned [enabled by default]
Note that I return a reference to the actual object, not a reference to a local variable copy of the object.
> Array<Cat> array(20)/*[20]*/ ;
See how this creates an array with 20 elements (the array is inside the Array class).
You can have array[20], but it's a completely different animal, and would need array[x][y] to subscript it!