C++案例 自定义数组

#include <string>
#include <iostream>
#include <algorithm>
#include <initializer_list>
using namespace std;

template<class T>
class myArray
{
	// 类模板 友元 重载 外部类实现
	// cout << array << endl;
	friend ostream& operator<< <T>(ostream& cout, const myArray<T>& array);
public:
	myArray(int size) {
		this->m_size = size;
		pAddress = new T[size]; 
	}

	myArray(const myArray<T>& array) {
		this->m_size = array.m_size;
		this->pAddress = new T[array.m_size]; 
		copy(array.pAddress, array.pAddress + array.m_size, this->pAddress);
	}

	~myArray() {
		if (pAddress != nullptr) {
			delete[] pAddress;  
			pAddress = nullptr;
		}
	}
	// array = {1,2,3,4,5}
	myArray& operator=(initializer_list<T> list) {
		if (this->pAddress != nullptr) {
			delete[] this->pAddress;
			this->pAddress = nullptr;
		}
		this->m_size = list.size();

		this->pAddress = new T[m_size];
		copy(list.begin(), list.end(), this->pAddress);
		return *this;
	}
	// array1 = array2
	myArray& operator=(const myArray<T>& array) {
		if (this != &array) {  // 自赋值检查
			if (this->pAddress != nullptr) {
				delete[] this->pAddress;  
				this->pAddress = nullptr;
			}
			this->m_size = array.m_size;
			this->pAddress = new T[array.m_size]; 
			copy(array.pAddress, array.pAddress + array.m_size, this->pAddress);
		}
		return *this;
	}
	// array = (T *)arr
	myArray& operator=(const T* array) {
		for (int i = 0; i < m_size; i++) {
			pAddress[i] = array[i];
		}
		return *this;
	}
	// array[0]
	T &operator[](int num) {
		return this->pAddress[num];
	}
	// 尾插法

	// 尾删法

private:
	T* pAddress;
	int m_size;
};


template<class T>
ostream& operator<<(ostream& cout, const myArray<T>& array) {
	cout << "[";
	for (int i = 0; i < array.m_size; i++) {
		cout << array.pAddress[i];
		if (i != array.m_size - 1) cout << ", ";  
	}
	cout << "]";
	return cout;
}

  测试

void test01() {
	myArray<int>arr1(5);
	arr1 = { 1,2,3,4,5 };

	myArray<int>arr2 = { 1,2,3,4,5 };

	int temp[] = { 1,2,3,4,5 };
	arr1 = temp;

	arr1[0] = 10;
	arr1 = arr2;

	cout << arr1 << endl;
}

  

posted @ 2025-10-23 21:47  秋秋秋秋秋寒  阅读(5)  评论(0)    收藏  举报