实现数组类Array,函数模板的简单应用

1、Array.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#pragma once
#include <iostream>
using namespace std;
 
template <typename Item>
class Array {
	int m_size;		// 实际长度
	int m_capacity;	// 容量大小
	Item *m_data;	// 数据结构指针
public:
	Array(int capacity = 0);
	bool insert(Item item);
	Item getItem(int index);
	Item operator[](int index);
	void display();
	~Array();
	friend ostream &operator<<<>(ostream &, Array<Item> &);
};
 
template <typename Item>
Array<Item>::~Array() {
	delete[] m_data;
}
 
template <typename Item>
Array<Item>::Array(int capacity) {
	if (capacity <= 0) return;
	m_capacity = capacity;
	m_data = new Item[capacity];
}
 
template <typename Item>
bool Array<Item>::insert(Item item) {
	if (m_size < m_capacity) {
		m_data[m_size] = item;
		m_size++;
		return true;
	}
	else {
		cout << "数组已满..." << endl;
		return false;
	}
}
 
template <typename Item>
Item Array<Item>::getItem(int index) {
	if (index < 0 || index >= m_size) {
		cout << "传入的索引不合法" << endl;
		return NULL;
	}
	else {
		return m_data[index];
	}
}
 
template <typename Item>
Item Array<Item>::operator[](int index) {
	return getItem(index);
}
 
template <typename Item>
void Array<Item>::display() {
	cout << "[";
	for (int i = 0; i < m_size; i++) {
		cout << m_data[i];
		if (i < m_size - 1) cout << ", ";
	}
	cout << "]";
}
 
template <typename Item>
ostream &operator<<<>(ostream &cout, Array<Item> &arr) {
	arr.display();
	return cout;
}

2、main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include "Array.hpp"
using namespace std;
 
 
 
int main() {
	Array<int> arr(4);
	arr.insert(3);
	arr.insert(5);
	arr.insert(6);
	arr.insert(9);
	cout << arr << endl;
	system("pause");
	return 0;
}

3、执行结果:

[3, 5, 6, 9]
请按任意键继续. . .

发表评论