C++类的设计与实现(对象数组)

//array,h
#pragma once

#include<iostream>
using namespace std;

class Array
{
public:
	Array(int length);
	Array(const Array& obj);
	~Array();
public:
	void setdata(int index, int data);
	int getdata(int index);
	int getlength();
private:
	int m_lentgh;
	int *m_space;
};
//array.cpp
#include"Array.h"
	
Array::Array(int length)
{
	if (length < 0)
	{
		m_lentgh = 0;
		m_space = new int[m_lentgh];
	}
	m_lentgh = length;
	m_space = new int[m_lentgh];
}
Array::Array(const Array& obj)
{
	this->m_lentgh = obj.m_lentgh;
	this->m_space = new int[m_lentgh];
	for (int i = 0; i < m_lentgh; i++)
	{
		this->m_space[i] = obj.m_space[i];
	}
}
Array::~Array()
{
	if (m_space != NULL)
	{
		delete[] m_space;
		m_space = NULL;
	}
}
//t1.setdata(i,i)
void Array::setdata(int index, int data)
{
	m_space[index] = data;
}
int Array::getdata(int index)
{
	return m_space[index];
}
int Array::getlength()
{
	return m_lentgh;
}
//Myarray.cpp
#include<iostream>
#include"Array.h"
using namespace std;

int main()
{
	Array t1(10);
	for (int i = 0; i < t1.getlength(); i++)
	{
		t1.setdata(i, i);
	}
	/*for (int i = 0; i < t1.getlength(); i++)
	{
		cout << "t1="<<t1.getdata(i)<< endl;
	}*/

	Array t2(t1);
	for (int i = 0; i < t2.getlength(); i++)
	{
		cout << "t2=" << t2.getdata(i) << endl;
	}

	system("pause");
}

猜你喜欢

转载自blog.csdn.net/error0_dameng/article/details/82082092