版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31339221/article/details/77581595
包含[] = == != 的重载
int& operator[](int i);
Array& operator=(Array &p);
bool operator==(Array &p);
bool operator!=(Array &p);
测试程序:
#include "iostream"
#include "MyArray.h"
using namespace std;
void main()
{
Array a1(10);
Array a3(20);
//输出a1
cout<<"输出a1"<<endl;
//cout<<a1.length()<<endl;
for(int i = 0;i<a1.length();i++)
{
//a1.setData(i,i);
a1[i] = i;
}
for(int i = 0;i<a1.length();i++)
{
cout<<a1[i]<<" ";
}
a3 = a1;
//输出a2
cout<<"输出a2"<<endl;
for(int i = 0;i<a3.length();i++)
{
cout<<a3[i];
}
if(a3 == a1)
printf("\nok\n");
else
printf("\n...\n");
if(a3 != a1)
printf("\nok\n");
else
printf("\n...\n");
system("pause");
}
函数 MyArray.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 valude);
int getData(int index);
int length();
int& operator[](int i);
Array& operator=(Array &p);
bool operator==(Array &p);
bool operator!=(Array &p);
private:
int m_length;
int *m_space;
};
函数实现:MyArray.c
#include "MyArray.h"
Array::Array(int length)
{
if(length < 0)
{
length = 0;
}
m_length = length;
m_space = new int[m_length];
}
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;
//cout<<"调用析构函数"<<endl;
m_length = 0;
}
}
void Array::setData(int index,int valude)
{
m_space[index] = valude;
cout<<valude<<endl;
}
int Array::getData(int index)
{
return m_space[index];
}
int Array::length()
{
return m_length;
}
int& Array::operator[](int i)
{
return m_space[i];
}
Array& Array::operator=(Array &p)
{
if(this->m_space != NULL)
{
delete[] m_space;
m_length = 0;
}
m_length = p.m_length;
m_space = new int[m_length];
for(int i=0;i<m_length;i++)
{
m_space[i] = p.m_space[i];
}
return *this;
}
bool Array::operator==(Array &p)
{
if(this->m_length != p.m_length)
{
return false;
}
for(int i=0;i<this->m_length;i++)
{
if(m_space[i] != p.m_space[i])
return false;
}
return true;
}
bool Array::operator!=(Array &p)
{
/* //方法1
if(*this == p)
return false;
return true;*/
//方法2
return !(*this == p);
}
请使用手机"扫一扫"x