As self-exercise, I have written this simple code:
#include <iostream>
int gIndex = 3;
template <class T> class Array
{
public:
explicit Array(int size);
T& operator[](int i) { return m_data[i]; }
T operator[](int i) const { return m_data[i]; }
T getAnchorPoint() const { return m_data[m_anchor]; }
private:
T* m_data;
int m_size;
int& m_anchor;
};
template <class T> Array<T>::Array(int size) : m_size(size), m_data(new T[size])
{
memset(m_data, 0, size*sizeof(T));
m_anchor = gIndex;
}
int main()
{
Array<double> a(10);
return 0;
}
I got a compilation error , which says:
error C2758: 'Array<T>::m_anchor' : must be initialized in constructor base/member initializer list
It has never happened , what brings me to ask this question:
Must any class-member reference type be initialized in the constructor initialization list?
If so, why? Is that related somehow to the fact that a reference type can never be reassigned?
Are there more types that must be initialized in constructor initialization list?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…