字定义数组类

MyArray.h 

#pragma once
#include<iostream>
using namespace std;
class MyArray
{
public:
	MyArray();
	MyArray(int len);
	MyArray(const MyArray &another);
	~MyArray();


	void setDate(int index, int data);
	int getData(int index);
	int getLen();
private:
	int len;
	int *space;
};

MyArray.cpp 

#include "MyArray.h"



MyArray::MyArray()
{
	cout << "MyArray(),,," << endl;
	this->len = 0;
	this->space = NULL;
}
MyArray::MyArray(int len) {

	if (len <= 0)
	{
		this->len = 0;
		return;
		}
	else {
		this->len = len;
		//给space开辟一个空间
		this->space = new int[this->len];
		cout << "MyArray::MyArray(int len)....." << endl;
	}
}
MyArray::MyArray(const MyArray &another) {
	
	if (another.len >= 0) {
		this->len = another.len;
		//深拷贝
		this->space = new int[this->len];
		for (int i = 0; i < this->len; i++) {
			this->space[i] = another.space[i];
		}
		cout << "MyArray::MyArray(const MyArray &another)....." << endl;
	}
	
}
MyArray::~MyArray() {

	if (this->space != NULL) {
		delete[] this->space;
		this->space = NULL;
		len = 0;
		cout << "MyArray::~MyArray()....." << endl;
	}
}


void MyArray::setDate(int index, int data) {
	if (this->space != NULL) {
		this->space[index] = data;
	}
	
}
int MyArray::getData(int index) {
	return this->space[index];
}
int MyArray::getLen() {
	return this->len;
}

main.cpp

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include "MyArray.h"
using namespace std;
int main()
{
	MyArray array1(10);//开辟10元素的数组
	for (int i = 0; i < 10; i++)
	{
		array1.setDate(i, i + 10);
	}
	cout << "------------" << endl;
	cout << "array1:" << endl;
	for (int i = 0; i < 10; i++)
	{

		cout << array1.getData(i) <<" ";
	}
	cout << endl;

	MyArray array2 = array1;

	cout << "array2" << endl;
	for (int i = 0; i < array2.getLen(); i++) {
		cout << array2.getData(i) << " ";
	}
	cout << endl;
	return 0;
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值