此案例,实现了数组类的操作符重载,包含 [] 和 = 运算符。实现如下:
首先MyArray.h的代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
class Array{
public:
int &operator[](int i);
Array &operator=(Array &a2);
Array(int length);
Array(const Array& obj);
~Array();
public:
void setData(int index,int value);
int getData(int index);
int length();
private:
int m_length;
int *m_space;
};
MyArray.cpp代码:
#include"stdafx.h"
#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 < obj.m_length; i++){//数组元素赋值
this->m_space[i] = obj.m_space[i];
}
}
Array::~Array(){
if (m_space != NULL){
delete[] m_space;
m_length = 0;
}
}
//a1.setData(i,j);
void Array::setData(int index, int value){
m_space[index] = value;
}
int Array::getData(int index){
return m_space[index];
}
int Array::length(){
return m_length;
}
int &Array::operator[](int i){
//[]重载
return this->m_space[i];
}
Array &Array::operator=(Array &a2){
//=重载
if (this->m_space != NULL){
delete[]m_space;
m_length = 0;
}
m_space = new int[a2.m_length];
m_length = a2.m_length;
for (int i = 0; i < m_length;i++)
m_space[i] = a2[i];
return *this;
}
然后包含main函数的测试.cpp
// 数组类的实现与训练.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "MyArray.h"
int _tmain(int argc, _TCHAR* argv[])
{
Array a1(10);
for (int i = 0; i < a1.length(); i++){
//a1.setData(i,i);
a1[i]=i;
//Array &a1.operator[](int i);
}
for (int i = 0; i < a1.length(); i++){
//cout << a1.getData(i) << " ";
cout << a1[i] << " ";
}
Array a2 = a1;//=操作符重载
//Array &a1.operator=(Array &a2);
for (int i = 0; i < a2.length(); i++){
//cout << a2.getData(i) << " ";
cout<<a2[i]<<" ";
}
return 0;
}