赞
踩
- #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;
- }
-

运行结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。