Make your own free website on Tripod.com
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <iterator>
 4 #include <vector>
 5 
 6 using namespace std;
 7 
 8 template<typename T>
 9 class Basket {
10 	private:
11 		vector<T> items;
12 		int numberOfItems;
13 	public:
14 		//explicit prevents implicit type-casting
15 		explicit Basket() : items(0), numberOfItems(0) {
16 		}
17 
18 		Basket &operator=(const Basket<T> &bas) {
19 			items = bas.items;
20 			numberOfItems = bas.numberOfItems;
21 		}
22 
23 		//return the value at "pos" element of items
24 		T operator[](int pos) const {
25 			return items[pos];
26 		}
27 
28 		//allows for "cout << Basket_object"
29 		friend ostream &operator<<(ostream &os, const Basket<T> &obj) {
30 			copy(obj.items.begin(), obj.items.end(), ostream_iterator<T>(os, " "));
31 
32 			return os;
33 		}
34 
35 		//add item to basket
36 		void addItem(const T &item) {
37 			items.push_back(item);
38 			++numberOfItems;
39 		}
40 
41 		int getNumberOfItems() const {
42 			return numberOfItems;
43 		}
44 
45 		~Basket() {
46 			--numberOfItems;
47 		}
48 };
49 
50 int main() {
51 	Basket<int> bi;
52 
53 	for(int x = 0; x < 5; x++)
54 		bi.addItem(x + 1);
55 
56 	cout << bi << endl;
57 	cout << "Items in basket: " << bi.getNumberOfItems() << endl;
58 
59 	cout << "2nd item = " << bi[1] << endl;
60 	
61 	return 0;
62 }
63 
64 
65 
66 		


syntax highlighted by Code2HTML, v. 0.9.1