模板template--typename T ,int N

1.h
#ifndef _1_H_
#define _1_H_

template 
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 
ARRAY::ARRAY()
{
	length=N;
}

template 
bool ARRAY::setvalue(int index,T value)
{	
	bool ret=0;
	if( (index0) )
	{
		array[index] = value;
		ret=1;
	}
	return ret;
}

template 
bool ARRAY::getvalue(int index,T& value)
{
	bool ret=0;
	if( (index0) )
	{
		value = array [index];
		ret=1;
	}
	return ret;

}
template 
T& ARRAY::operator[]( int index)
{
		if( (index0) )
	{
		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::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 
int ARRAY::getlen()
{
	return length;
}
#endif
1.c
#include
#include"1.h"
using namespace std;

int main( )
{
	ARRAYtest;
	int l=test.getlen();
	cout<<"len =="<


你可能感兴趣的:(c++)