c++は配列クラスを実現する

3021 ワード

先生が授業中にノックした例は,バグを修正した.
1配列クラスは、対応する場所での要素の削除と挿入をサポートします.
2静的オブジェクトは静的メンバー関数のみを呼び出すため、[]符号のリロードには2つのバージョンが使用されます.
クラスヘッダファイル
 
#pragma once
class MyVect
{
public:
	MyVect();
	MyVect(int n);
	MyVect(const MyVect& other);			//      
	MyVect& operator = (const MyVect& rhs); //     
	void push_back(double var);			
	double pop_back();
	void insert(int n, double var);
	void erase(int n);
	void reallocate();					    //      
	void clear();
	void print();
	double& operator[](int n);				//  [] 
	const double& operator[](int n)const;   //const    ,    const
	virtual ~MyVect();
private:
	double* date;	   //    
	int date_size;	   //      
	int date_capacity; //    
};


 
 
クラスソースファイル
 
#include "MyVect.h"
#include
using namespace std;

MyVect::MyVect()
{
	date = nullptr;
	date_size = 0;
	date_capacity = 0;
}

MyVect::MyVect(int n)
{
	date_size = n;
	date_capacity = 2 * n + 1;
	date = new double[date_capacity];
}

double& MyVect::operator[](int n)
{
	return date[n];
}

const double& MyVect::operator[](int n) const //           
{
	return date[n];
}

MyVect& MyVect::operator=(const MyVect& rhs) //     
{
	if (this == &rhs)
	{
		return *this;
	}
	date_capacity = rhs.date_capacity;
	date_size = rhs.date_size;
	if (date != nullptr)
	{
		delete[] date;
	}
	date = new double[date_capacity];
	for (int i = 0; i < rhs.date_size; i++)
	{
		date[i] = rhs.date[i];
	}
	return *this;
}

MyVect::MyVect(const MyVect& other)
{
	this->date_size = other.date_size;
	this->date_capacity = other.date_capacity;
	date = new double[date_capacity];
	for (int i = 0; i < date_size; i++)
	{
		date[i] = other.date[i];
	}
}
void MyVect::reallocate()  //      
{
	if (date_size == date_capacity)
	{
		double* old = date;
		date_capacity = 2 * date_size + 1;
		date = new double[date_capacity];
		for (int i = 0; i < date_size; i++)
		{
			date[i] = old[i];
		}
		if (old != nullptr)
			delete[] old;
	}
}

void MyVect::push_back(double var)
{
	this->reallocate();
	date[date_size] = var;
	date_size++;
}

double MyVect::pop_back()
{
	double out = date[date_size-1];
	date_size--;
	return out;
}

void MyVect::insert(int n, double var)
{
	reallocate();
	for (int i = date_size; i >n; i--)
	{
		date[i] = date[i-1];
	}
	date[n] = var;
	date_size++;
}

void MyVect::erase(int n)
{
	for (int i = n; i < date_size; i++)
	{
		date[i] = date[i + 1];
	}
	date_size--;
}

void MyVect::clear()
{
	date_size = 0;
	date_capacity = 0;
	if (date != nullptr)
		delete [] date;
	date = nullptr; //     ,                
}

void MyVect::print()
{
	for (int i = 0; i < date_size; i++)
		cout << date[i] << '\t';
	cout << endl;
}

MyVect::~MyVect()
{
	date_size = 0;
	date_capacity = 0;
	if (date!=nullptr)
	{
		delete[] date;
	}
	date = nullptr;
	//cout << "   !" << endl;
}