数组类——类的设计和实现




第一步:类的设计

MyArray.h

#pragma  once

#include<iostream>
using namespace std;

class Array//创建一个Arry类
{
public:
	Array(int length);//有参构造函数
	Array(const Array&obj );//拷贝构造函数
	~Array();//析构函数
public:
	void setData(int index,int valude);//设置数据
	int getData(int index);//获得数据
	int length();//获得长度
protected:
	

private:
	int m_length;
	int *m_space;
};

第二步:写类的实现

MyArray.cpp

#include "MyArray.h"


Array::Array(int length)
{
	if (length < 0)
	{
		m_length = 0;
	}
	m_length =length;
	m_space = new int[m_length];//指针变量 = new 类型[表达式];从堆内存分配一块“类型”大小的内存空间,返回首地址
	
}
//Array a2 = a1;
Array::Array(const Array&obj )//拷贝构造函数
{
	this->m_length = obj.m_length;
	this->m_space = new int [this->m_length];// 分配内存空间
	for (int i=0;i<m_length;i++)//数据元素赋值
	{
		this->m_space[i] = obj.m_space[i];
	}
}
Array::~Array()
{
	if (m_space != NULL)
	{
		delete[] m_space;
		m_length = 0;
	}
}
//a1.setData(i,i);
void Array::setData(int index,int valude)
{
	m_space[index] = valude;
}
int Array::getData(int index)
{
	return m_space[index];
}
int Array::length()
{
	return m_length;
}
Test_MyArray2.cpp
#include<iostream>
using namespace std;
#include "MyArray.h"
//类的框架设计设计完毕
//累的测试案例
int main()
{
	Array a1(10);
	
	for (int i=0;i<a1.length();i++)
	{
		a1.setData(i,i);
	}
	cout<<"输a1: "<<endl;
	for (int i=0;i<a1.length();i++)
	{
		cout<<a1.getData(i)<<" ";
	}


	Array a2 = a1;
	cout<<"输a2:"<<endl;
	for (int i=0;i<a1.length();i++)
	{
		cout<<a1.getData(i)<<" ";
	}
	
	system("pause");
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值