Nov 25, 2017 at 9:13pm Nov 25, 2017 at 9:13pm UTC
Hello everyone.
i'am making a simple class for dynamic arrays in C++:
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
#include <iostream>
using namespace std;
template <class T>
class Array {
private :
T *arr;
public :
int length=0;
Array(int size) {
length=size;
arr=new T[length];
}
void push(T value) {
arr[length++]=value;
}
void pop() {
length--;
}
T operator [](int index) {
return arr[index];
}
//i'am not sure how to implement the >> operator here...
};
int main() {
int size=4;
Array<int > arr(size);
for (int i=0;i<size;i++) {
cin >> arr[i]; //i don't know how to handle this part...
}
}
So as you can see,i need to know how to implement the >> operator to make it handle the custom array elements input.
Thanks in advance.
Last edited on Nov 25, 2017 at 9:54pm Nov 25, 2017 at 9:54pm UTC
Nov 26, 2017 at 12:55am Nov 26, 2017 at 12:55am UTC
T& operator [](int index)
return a reference (not a value), so you can operate on the element.
cin >> arr[i];
you need to differentiate element from container
`arr' is an Array, the container
`arr[i]' is an element, in this case an `int'.
reading an int is known, you don't need to overload operator>>
Last edited on Nov 26, 2017 at 12:56am Nov 26, 2017 at 12:56am UTC