C++:赋值运算符和下标运算符重载示例

#pragma once
class IntArray
{
public:
	//IntArray();
	IntArray(int = 10);			//默认形参
	~IntArray();
	IntArray& operator = (const IntArray &);	
							//重载赋值运算符,括号内为引用;返回对象的类型
	int& operator[](int);		//重载下标运算符,返回int型
	void DisplayArray();
private:
	int m_size;
	int *m_ptr;

};

#include "stdafx.h"
#include "IntArray.h"

#include <assert.h>
#include<iostream>
using namespace std;
//IntArray::IntArray()
//{
//}

IntArray::IntArray(int arraySize)			
{
	m_size = (arraySize > 0 ? arraySize : 10);
	m_ptr = new int[m_size];		//新申请一块空间
	assert(m_ptr != 0);
	for (int i = 0; i < m_size; i++)
	{
		m_ptr[i] = 0;
	}
}
IntArray::~IntArray()
{
	delete[] m_ptr;
}

//重载赋值运算符,括号内为引用;返回对象的类型
IntArray& IntArray::operator = (const IntArray &right)
{
	if (&right != this)		//检测自赋值
	{
		if (m_size != right.m_size)
		{
			delete[] m_ptr;	//释放左操作数指针
			m_size = right.m_size;
			m_ptr = new int[m_size];
			assert(m_ptr != 0); 

		}
		for (int i = 0; i < m_size; i++)
		{
			m_ptr[i] = right.m_ptr[i];
		}
		return *this;

	}

}

int& IntArray::operator[](int subscript)		//重载下标运算符,返回int型
{
	assert(0 <= subscript && subscript < m_size);	//下标越界,退出程序
	return m_ptr[subscript];
}
void IntArray::DisplayArray()
{
	for (int i = 0; i < m_size; i++)
	{
		cout << m_ptr[i] << " ";
	}
	cout << endl;
}
// operator_chognzai.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "IntArray.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	IntArray arrayA;
	IntArray arrayB(5);
	for (int i = 0; i < 5; i++)
	{
		arrayB[i] = i+1;		//调用下标运算符函数
		//相当于执行:arrayB.m_ptr[i] = i+1
	}
	cout << "数组ArrayA为:" << endl;
	arrayA.DisplayArray();
	cout << "数组ArrayB为:" << endl;
	arrayB.DisplayArray();
	arrayA = arrayB;		//调用赋值运算符函数
	cout << "执行arrayA = arrayB后,数组arrayA 为:" << endl;
	arrayA.DisplayArray();

	getchar();
	return 0;
}

运行结果:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值