操作符[]重载

 1 #ifndef _INTARRAY_H_
 2 #define _INTARRAY_H_
 3 class IntArray{
 4 private:
 5   int m_length;
 6   int* m_pointer;
 7   IntArray(int len);
 8   IntArray(const IntArray& obj);
 9   bool construct();//作用:数组申请内存、赋初值
10 public:
11   static IntArray* NewInstance(int length);//创建对象函数,加static的作用??
12   bool get(int index,int&value);
13   bool set(int index,int value);
14   int& operator[](int index);//操作符重载函数
15   int length();//老是忘记获取数组长度的函数
16   IntArray& self();//返回自身的成员函数
17   ~IntArray();
18 };
19 #endif
//11行如果不加static报错显示为:

error: cannot call member function ‘IntArray* IntArray::NewInstance(int)’ without object
IntArray*a = IntArray::NewInstance(5);
^

 
 1 #include"IntArray.h"
 2 IntArray::IntArray(int len){
 3         m_length = len;//通过构造函数给定数组长度
 4 }
 5 //为数组申请空间并赋初值,想下该函数是私有成员的好处;二阶构造函数的第二阶段--申请资源
 6 bool IntArray::construct(){
 7         bool ret = true;
 8         m_pointer = new int[m_length];
 9         if(m_pointer){
10                 for(int i = 0;i< m_length;i++){
11                         m_pointer[i] = i;
12                 }
13         }else{
14                 ret = false;
15         }
16         return ret;
17 }
18 int IntArray::length(){
19         return m_length;
20 }
21 IntArray* IntArray::NewInstance(int length){
22         IntArray* ret = new IntArray(length);
23         if(!(ret && ret->construct())){
24                 delete ret;
25                 ret = 0;//??????为什么非得是0,NULL就是不行?
26         }
27         return ret;
28 }
29 bool IntArray::get(int index,int&value){
30       //和数组下标index相关的都要注意下标判断的越界问题
31         bool ret = (0<=index && index < length());
32         if(ret){
33                 value = m_pointer[index];
34         }
35         return ret;
36 }
37 bool IntArray::set(int index,int value){
38         bool ret = ((0 <=  index)&&(index < length()));
39         if(ret){
40                 m_pointer[index] = value;
41         }
42         return ret;
43 }
44 int& IntArray::operator[](int index){
45         return m_pointer[index];
46 }
47 IntArray& IntArray::self(){
48         return *this;//返回当前数组对象
49 }
50 IntArray::~IntArray(){
51         delete[]m_pointer;
52 }
 1 #include<iostream>
 2 #include<string>
 3 #include"IntArray.h"
 4 #include<stdio.h>
 5 using namespace std;
 6 int main(){
 7         //IntArray a[5];   X
 8         IntArray*a = IntArray::NewInstance(5);
 9         if(a != NULL){
10                 //给a所指向堆空间的对象起别名这样可以避免在C++中指针的使用,秒啊~
11                 IntArray& array = a->self();
12                 cout << array.length() << endl;
13         for(int i=0;i < array.length();i++){
14                 cout << array[i] << endl;
15                 }
16         }//注意array对象的作用域范围,傻x!!
17         delete a;
18         return 0;
}



原文地址:https://www.cnblogs.com/DXGG-Bond/p/11871304.html