Write a class template that inputs the index of the array and displays the value in the specified index.
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Array
{
private:
int length;
T *data;
public:
Array(int length,T *data)
{
if(length > 0){
this->data = data;
this->length = length;
}
}
~Array(){
}
T& operator[](int index)
{
if(index >= 0 && index < length){
return data[index];
}
}
};
int main () {
int intNumbers[] = {10, 5, 8, 14, 12,32,85,47,66,12};
Array<int> intArray(10,intNumbers);
float floatNumbers[] = {12.6, 25.8, 36.35, 26.95, 11.41,85.12,39.62,85.12,47.95,15.74};
Array<float> floatArray(10,floatNumbers);
cout<<"Integer numbers:\n";
for(int i=0;i<10;i++){
cout<<intNumbers[i]<<" ";
}
cout<<"\nValue at index 5 = "<<intArray[5];
cout<<"\nFloat numbers:\n";
for(int i=0;i<10;i++){
cout<<floatNumbers[i]<<" ";
}
cout<<"\nValue at index 8 = "<<floatArray[8]<<"\n\n";
system("pause");
return 0;
}
Comments
Leave a comment