天天看點

[]的重載練習&數組封裝

Marry.h代碼為

#define _CRT_SECURE_NO_WARNINGS
#pragma once
#include <iostream>
#include <string>
using namespace std;

class m_arry
{
private:
	int *p_addr;	// 指向數組的起始指針
	int m_size;		// 數組大小
	int m_capacity; // 數組容量
public:
	m_arry ();
	m_arry(int v_capacity);	
	m_arry(const m_arry& v_arry); // 拷貝構造函數
	~m_arry();

	// 尾插法
	void push_back(int val);
	// 設定值
	void set_data(int index,int val);
	// 擷取值
	int get_data(int index) const;
	// 擷取容量
	int get_capacity() const;
	// 擷取大小
	int get_size() const;
	// 顯示目前數組的元素
	void show_element() const;

	int& operator[](int index);
	
};
           

Marry.cpp代碼為

#include "MyArry.h"

// 預設構造函數
m_arry::m_arry ()
{
	cout<<"預設構造函數"<<endl;
	this->m_size = 0;
	this->m_capacity = 100;
	this->p_addr = new int[this->m_capacity ];
}

// 有參構造函數
m_arry::m_arry (int v_capacity)
{
	cout<<"有參構造函數"<<endl;
	this->m_size = 0;
	this->m_capacity = v_capacity;
	this->p_addr = new int[this->m_capacity];
	cout<< "this->p_addr的位址為" <<this->p_addr<<endl;
}

// 拷貝構造函數
m_arry::m_arry(const m_arry& v_arry)
{
	cout <<"拷貝構造函數"<<endl;
	this->p_addr = new int[v_arry.m_capacity];
	this->m_size = v_arry.m_size;
	this->m_capacity = v_arry.m_capacity;
	for (int i=0;i<v_arry.m_size;i++)
	{
		this->p_addr[i] = v_arry.p_addr[i];
	}
}

m_arry::~m_arry()
{
	cout<<"析構函數"<<endl;
	if (this->p_addr != NULL)
	{
		delete[] this->p_addr;
		this->p_addr = NULL;
	}
}
// 尾插法
void m_arry::push_back(int val)
{
	if (this->m_size > this->m_capacity)
	{
		cout<<"尾插越界了"<<endl;
	}
	*(this->p_addr+this->m_size) = val;
	this->m_size++;
}

// 設定值
void m_arry::set_data(int v_index,int val)
{
	if (v_index > this->m_size)
	{
		cout<<"尾插越界了"<<endl;
	}
	this->p_addr[v_index]= val;
}

// 擷取值
int m_arry::get_data(int index) const
{
	return this->p_addr[index];
}
// 擷取容量
int m_arry::get_capacity() const
{
	return this->m_capacity;
}

// 擷取大小
int m_arry::get_size() const
{
	return this->m_size;
}

// 顯示目前數組的所有元素
void m_arry::show_element() const
{
	for (int i=0;i<this->m_size;i++)
	{
		cout<<this->p_addr[i]<<endl;
	}
}

int& m_arry::operator[](int index)
{
	return this->p_addr[index];
}

           

main.cpp代碼為

#define _CRT_SECURE_NO_WARNINGS
#include "MyArry.h"

void test_01(void)
{
	/*m_arry arr1(30);
	arr1.push_back(1);
	arr1.push_back(5);
	arr1.push_back(10);
	arr1.set_data(2,100);
	cout<<arr1.get_size()<<endl;
	cout<<arr1.get_data(0)<<endl;

	arr1.show_element();*/
	//
	//m_arry arr2 = arr1;
	//arr2.show_element();

	//m_arry arr3;
	//arr3.show_element();
	
	//m_arry * array = new m_arry[5];  // 注意
	//堆區建立數組
	m_arry * arr1 = new m_arry(30);
	arr1->push_back(10);
	arr1->push_back(20);
	arr1->push_back(30);
	arr1->push_back(1000);
	(*arr1)[2]=50;
	(*arr1).operator[](2)=60;
	arr1->show_element();
	//m_arry * arr2 = new m_arry(*arr1);
	//m_arry arr3 = *arr1;
	/*cout<< "arr1 為" <<arr1<<endl;
	delete arr1;*/



}

int main()
{
	test_01();

	system("pause");
	return EXIT_SUCCESS;
}
           

繼續閱讀