Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Hostgator 1 Penny

BlueHost Web Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

getflywheel wordpress hosting


Distribute your Resume to 500+ Job Boards & Recruiters


7,372 questions

10,373 answers

573 users

How to template class in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

#define SIZE 3

template <class T> class Test {
	T arr[SIZE];
public:
	Test(void)
	{
		for (int i = 0; i < SIZE; i++)
			arr[i] = i + 2;
	}
	T &operator[](int i);
	void print(void)
	{
		for (int i = 0; i < SIZE; i++)
			cout << arr[i] << " ";
		cout << endl;
	}
};

template <class T> T &Test<T>::operator[](int i)
{
	if (i < 0 || i > SIZE - 1)
		cout << "index " << i << " out of range" << endl;
	
	return arr[i];
}



int main()
{
	Test<int> int_array;
	Test<float> float_array;

	int_array.print();
	for (int i = 0; i < SIZE; i++)
		int_array[i] = i + 111;
	int_array.print();
	int_array[5] = 9999;

	float_array.print();
	for (int i = 0; i < SIZE; i++)
		float_array[i] = (float)i / 6 + 2;
	float_array.print();
	float_array[6] = 3.14;
	
	return 0;
}


/*
run:

2 3 4
111 112 113
index 5 out of range
2 3 4
2 2.16667 2.33333
index 6 out of range

*/

 




answered Mar 13 by avibootz
...