1.h #ifndef _1_H_ #define _1_H_ template <typename T,int N> class ARRAY { int length; T array[N]; public: ARRAY(); bool setvalue(int index,T value); bool getvalue(int index,T& value); int getlen(); T& operator[](int index); T operator[](int index)const; }; template <typename T,int N> ARRAY<T,N>::ARRAY() { length=N; } template <typename T,int N> bool ARRAY<T,N>::setvalue(int index,T value) { bool ret = 0; if( (index<N)&&(index>0) ) { array[index] = value; ret = 1; } return ret; } template <typename T,int N> bool ARRAY<T,N>::getvalue(int index,T& value) { bool ret = 0; if( (index<N)&&(index>0) ) { value = array [index]; ret = 1; } return ret; } template <typename T,int N> T& ARRAY<T,N>::operator[]( int index) { if( (index<N)&&(index>0) ) { return array [index]; }else{ return NULL;// ERROR /*----- NULL IS void* and invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’---- NULL IS RVALUE can do this----- const T& ARRAY<T,N>::operator[]( int index) but still warning 1.h:55:10: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null] SO I WILL CUT THE ELSE ,THEN COMPILE PASS. */ } } template <typename T,int N> int ARRAY<T,N>::getlen() { return length; } #endif
1.c #include<iostream> #include"1.h" using namespace std; int main( ) { ARRAY<int,10>test; int l=test.getlen(); cout<<"len =="<<l<<endl; if(test.setvalue(5,3)) cout<<"index =5 value=3"<<endl; int value; if (test.getvalue(5,value)) cout<<"index =5 value="<<value<<endl; cout<<"test[5]"<<test[5]<<endl; return 0; }