My understanding is typedef acts as a synonym for a type, or can be used as an alias for a particular type. Also, the simplified codes below built perfectly. The question here is if I change the second line in the main function to :
Array<int>::ArrayIter<T> pa = a.begin(); // substituting back the typedef “iterator” to its original form of ArrayIter<T>.
I get the following error message during compilation:
“ArrayIter” is not a member of “Array”
But the codes compiled perfectly using the “typedef” (iterator) notation. Why is “iterator” and ArrayIter suddenly not synonymous any more:
Reference codes below:
template<class T> class ArrayIter {
public:
ArrayIter(T* p) : m_p(p) {
}
private:
T* m_p;
};
template<class T> class Array {
public:
Array(int size) throw (const char*) {
if ( size > 0 ) {
m_p = new T[size];
m_size = size;
} else {
throw "Array: invalid array dimension";
}
}
// typedef and methods to support the new iterator for this class
typedef ArrayIter<T> iterator;
ArrayIter<T> begin() {
return ArrayIter<T>(m_p);
}
private:
T* m_p;
int m_size;
};
int main(int argc, char* argv[]) {
Array<int> a(10);
Array<int>::iterator pa = a.begin();
return 0;
}
As the error says,
ArrayIteris not a member ofArray: it’s a separate class, declared in the surrounding namespace. Therefore,Array<int>::ArrayIter<T>is invalid, and should just beArrayIter<int>.iteratoris a member ofArray, soArray<int>::iteratoris valid, and is an alias forArrayIter<int>.