在学习c++的过程中,我们经常使用到数组,那怎么去定义一个类去实现数组的功能呢?
我们先列出一些经常对数组进行的一些操作,
1、 创建一个指定容量的数组
2、 用已有的数组初始化另一个数组
3、 用已有的数组给另一个数组赋值
4、 给数组添加元素/给数组元素赋值
5、 获取数组指定元素的值
6、 输入一定数量的值,将值赋给数组
7、 输出数组
……
还有很多,本次只实现以上功能
以下是代码:
1、MyArray.h 文件 :MyArray 类的声明
#pragma once
#include <iostream>
using namespace std;
class MyArray
{
public:
// 构造函数
MyArray();
// 拷贝构造函数
MyArray(const MyArray&m);
// 有参构造函数
MyArray(int len);
// 析构函数
~MyArray();
// 设置值
void setData(int index, int data);
// 获取值
int getData(int index);
// 获取长度
int getLen()const;
// 重载赋值运算符
MyArray & operator =(const MyArray&);
// 重载 []
int & operator [](int i)const;
// 重载<<
friend ostream & operator << (ostream & os, const MyArray & ma);
// 重载>>
friend istream & operator >> (istream & is, MyArray & ma);
private:
int len; // 数组长度
int * space;// 指针 指向堆上的空间
};
2、MyArray.cpp 文件 :MyArray 类的实现
#include "MyArray.h"
// 构造函数
MyArray::MyArray()
{
this->len = 0; this->space = NULL;
}
// 拷贝构造函数
MyArray::MyArray(const MyArray&m)
{
this->len = m.len;
// 深拷贝
if (this->space == NULL)
{
this->space = new int[this->len];//申请分配新内存
}
for (int i = 0; i < this->len; i++)
{
this->space[i] = m.space[i];//拷贝值
}
}
//有参构造函数
MyArray::MyArray(int len)
{
if (len <= 0)
{
this->len = 0;
return;
}
else
{
this->len = len;
this->space = new int[this->len];
}
}
// 析构函数
MyArray::~MyArray()
{
if ((this->space) != NULL)
{
delete this->space;
this->space = NULL;
len = 0;
}
}
// 设置值
void MyArray::setData(int index, int data)
{
if (this->space != NULL)
{
this->space[index] = data;
}
}
// 获取值
int MyArray::getData(int index)
{
return this->space[index];
};
// 获取长度
int MyArray::getLen()const
{
return this->len;
};
// 重载赋值运算符
MyArray& MyArray::operator =(const MyArray&m)
{
if (this == &m)
{
return *this;
}
// 如果数组不为空,清空数组当前内容
if (this->space != NULL)
{
delete[] this->space;
this->space = NULL;
}
// 深拷贝
this->len = m.len;
this->space = new int[this->len];
for (int i = 0; i < this->len; i++)
{
this->space[i] = m.space[i];
}
return *this;
}
// 重载 []
int & MyArray::operator [](int i)const
{
return this->space[i];
}
// 重载 <<
ostream & operator << (ostream & os, const MyArray & ma)
{
for (int i = 0; i < ma.getLen(); i++)
{
os << ma[i] << " ";
}
return os;
}
// 重载 >>
istream & operator >> (istream & is, MyArray & ma)
{
cout << "请输入 " << ma.getLen() << " 个数" << endl;
for (int i = 0; i < ma.getLen(); i++)
{
is >> ma[i];
}
return is;
}
3、main 方法调用
#include <iostream>
#include "MyArray.h"
using namespace std;
void main()
{
MyArray arr1; // 声明数组
MyArray arr2(10); // 声明一个容量为10的数组
cin >> arr2; // 用输入值为数组赋值
cout << "arr2 : " << arr2 << endl; // 输出数组
MyArray arr3 = arr2;// 用已有的数组初始化另一个数组
cout << "arr3 : " << arr3 << endl; // 输出数组
arr1 = arr2; // 用已有的数组给另一个数组赋值
cout <<"arr1 : "<< arr1 << endl; // 输出数组
MyArray arr4(5); // 给数组添加元素/给数组元素赋值
for (int i = 0; i < 5; i++) { arr4[i] = i + 10; }
cout << "arr4 : " << arr4 << endl; // 输出数组
// 获取数组指定元素的值
cout << "arr4 [4] = " << arr4[4] << endl;
}
4、运行结果
以上。
感谢您的浏览