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

博客围绕C++类的设计与实现展开,重点涉及对象数组相关内容,属于信息技术领域中后端开发的C++编程范畴。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//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");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值