C++学习笔记:数组的操作符重载(包括[]和=运算符)

此案例,实现了数组类的操作符重载,包含 [] 和 = 运算符。实现如下:

首先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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值