测试.cpp
// 数组类_类的设计和测试程序.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include "myArray.h"
#include<iostream>
using namespace std;
//类的框架设计完毕
//类的测试案例
//重载[],返回值可以是3种不同的返回类型,至于选择什么,要看调用方式
//void operator[](int i)
//int operator[](int i)
//int& operator[](int i)
int main()
{
myArray a1(10);
//赋值
for (int i = 0; i < a1.length(); ++i)
{
//a1.setData(i, i);
//2
a1[i]=i;
}
//打印
cout << "打印数组a1" << endl;
for (int i = 0; i < a1.length(); i++)
{
//cout << a1.getData(i) << " ";
//1
cout<<a1[i]<<' ';
}
cout << endl;
myArray a2 = a1;
cout << "打印数组a2" << endl;
for (int i = 0; i < a2.length(); ++i)
{
cout << a2.getData(i) <<" ";
}
cout << endl;
//3
myArray a3(5);
{
a3 = a1;
a3 = a2 = a1;
cout << "\n打印数组a3: ";
for (int i = 0; i<a3.length(); i++)
{
cout << a3[i] << " ";
}
cout << endl;
//a3.operator=(a1)
//Array& operator=(Array &a1)
}
//功能4
if (a3 == a1)
{
cout << "相等" << endl;
}
else
{
cout << "不想等" << endl;
}
//5
if (a3 != a1)
{
printf("不相等\n");
}
else
{
printf("相等\n");
}
//
//a3.operator!=(a1)
// bool operator!=(Array &a1);
system("pause");
return 0;
}
myArray.h
#pragma once
class myArray
{
public:
myArray(int length);
myArray(const myArray& obj);
~myArray();
public:
void setData(int dex, int value);
int getData(int dex);
int length();
public:
//函数返回值当左值,需要返回一个引用
//函数返回值当左值,需要返回一个引用
//重载[]
int& operator[](int i);
//重载=
myArray& operator=(myArray &a1);
//重载==
bool operator==(myArray &a1);
//重载!=
bool operator!=(myArray &a1);
private:
int m_length;
int *m_space;
};
myArray.cpp
#include "myArray.h"
#include<stdio.h>
/*
private:
int m_length;
int *m_space;
*/
myArray::myArray(int length)
{
if (length < 0)
{
m_length = 0;
}
m_length = length;
m_space = new int[m_length];
}
//myArray a2=a1;
myArray::myArray(const myArray&obj)
{//手动实现深拷贝
this->m_length = obj.m_length;
this->m_space = new int[obj.m_length];
for (int i = 0; i < obj.m_length; ++i)
{
this->m_space[i] = obj.m_space[i];
}
}
myArray::~myArray()
{
if (m_space != NULL)
{
delete[]m_space;
m_length = -1;
}
}
void myArray::setData(int dex, int value)
{
m_space[dex] = value;
}
int myArray::getData(int dex)
{
return m_space[dex];
}
int myArray::length()
{
return m_length;
}
//1 2
int& myArray::operator[](int i)
{
return m_space[i];
}
//3 myArray a2 = a1;
//因为数组类中含有指针,所以在赋值的时候会有浅拷贝问题(在析构的时候会出问题)
//可以用重载=操作符解决这一问题
//重载=操作符的一般步骤:1.释放原来的内存空间2.根据a1大小给a2分配内存3.copy数据
myArray& myArray::operator=(myArray &a1)
{//为了支持链式(a3=a2=a1),左值不能是void,所以要返回引用
//1.
if (this->m_space != NULL)
{
delete[]m_space;
m_length = 0;
}
//2.
m_length = a1.m_length;
m_space = new int[m_length];
//3.
for (int i = 0; i < m_length; i++)
{
m_space[i] = a1[i];//因为[]操作符已经被重载过了,所以这里可以直接用
}
return *this;
}
//4 if (a3 == a1)
bool myArray::operator==(myArray &a1)
{
if (this->m_length != a1.m_length)
{
return false;
}
for (int i = 0; i <m_length; i++)
{
if (this->m_space[i]!=a1[i])
{
return false;
}
}
return true;
}
bool myArray::operator!=(myArray &a1)
{
/*
if (*this == a1)
{
return true;
}
else
{
return false;
}
*/
return !(*this == a1);
}