当前位置:   article > 正文

C++:赋值运算符和下标运算符重载示例_array 返回下标 运算符&

array 返回下标 运算符&
  1. #pragma once
  2. class IntArray
  3. {
  4. public:
  5. //IntArray();
  6. IntArray(int = 10); //默认形参
  7. ~IntArray();
  8. IntArray& operator = (const IntArray &);
  9. //重载赋值运算符,括号内为引用;返回对象的类型
  10. int& operator[](int); //重载下标运算符,返回int型
  11. void DisplayArray();
  12. private:
  13. int m_size;
  14. int *m_ptr;
  15. };
  1. #include "stdafx.h"
  2. #include "IntArray.h"
  3. #include <assert.h>
  4. #include<iostream>
  5. using namespace std;
  6. //IntArray::IntArray()
  7. //{
  8. //}
  9. IntArray::IntArray(int arraySize)
  10. {
  11. m_size = (arraySize > 0 ? arraySize : 10);
  12. m_ptr = new int[m_size]; //新申请一块空间
  13. assert(m_ptr != 0);
  14. for (int i = 0; i < m_size; i++)
  15. {
  16. m_ptr[i] = 0;
  17. }
  18. }
  19. IntArray::~IntArray()
  20. {
  21. delete[] m_ptr;
  22. }
  23. //重载赋值运算符,括号内为引用;返回对象的类型
  24. IntArray& IntArray::operator = (const IntArray &right)
  25. {
  26. if (&right != this) //检测自赋值
  27. {
  28. if (m_size != right.m_size)
  29. {
  30. delete[] m_ptr; //释放左操作数指针
  31. m_size = right.m_size;
  32. m_ptr = new int[m_size];
  33. assert(m_ptr != 0);
  34. }
  35. for (int i = 0; i < m_size; i++)
  36. {
  37. m_ptr[i] = right.m_ptr[i];
  38. }
  39. return *this;
  40. }
  41. }
  42. int& IntArray::operator[](int subscript) //重载下标运算符,返回int型
  43. {
  44. assert(0 <= subscript && subscript < m_size); //下标越界,退出程序
  45. return m_ptr[subscript];
  46. }
  47. void IntArray::DisplayArray()
  48. {
  49. for (int i = 0; i < m_size; i++)
  50. {
  51. cout << m_ptr[i] << " ";
  52. }
  53. cout << endl;
  54. }
  1. // operator_chognzai.cpp : 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include "IntArray.h"
  5. #include<iostream>
  6. using namespace std;
  7. int _tmain(int argc, _TCHAR* argv[])
  8. {
  9. IntArray arrayA;
  10. IntArray arrayB(5);
  11. for (int i = 0; i < 5; i++)
  12. {
  13. arrayB[i] = i+1; //调用下标运算符函数
  14. //相当于执行:arrayB.m_ptr[i] = i+1
  15. }
  16. cout << "数组ArrayA为:" << endl;
  17. arrayA.DisplayArray();
  18. cout << "数组ArrayB为:" << endl;
  19. arrayB.DisplayArray();
  20. arrayA = arrayB; //调用赋值运算符函数
  21. cout << "执行arrayA = arrayB后,数组arrayA 为:" << endl;
  22. arrayA.DisplayArray();
  23. getchar();
  24. return 0;
  25. }

运行结果:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/406196
推荐阅读
相关标签
  

闽ICP备14008679号