赞
踩
- #include <iostream.h>
-
- class aInteger
- {
- public:
- aInteger(int size)
- {
- sz = size;
- a = new int[size];
- }
-
- int& operator [] (int i);
-
- ~aInteger()
- {
- delete []a;
- }
- private:
- int* a;
- int sz;
- };
-
- int& aInteger::operator [](int i)
- {
- if (i < 0 || i > sz)
- {
- cout << "error, leap the pale" << endl;
- }
-
- return a[i];
- }
-
- int main()
- {
- aInteger arr(10);
- for (int i = 0; i < 10; i++)
- {
- arr[i] = i+1;
- cout << arr[i] << endl;
- }
-
- int n = arr.operator [] (2);
- cout << "n = " << n << endl;
-
- return 0;
- }
- //**********************************
- //*** 下标重载运算符 ***
- //**********************************
-
- #include <iostream.h>
-
- class charArray
- {
- public:
- charArray(int len)
- {
- length = len;
- buffer = new char[length];
- }
-
- int getLength()
- {
- return length;
- }
-
- char& operator[](int i);
-
- ~charArray()
- {
- delete[]buffer;
- }
- private:
- int length;
- char* buffer;
- };
-
- char& charArray::operator[] (int i)
- {
- static char ch = 0;
- if (i >= 0 && i < length)
- return buffer[i];
- else
- {
- cout << "out of range!" << endl;
- return ch;
- }
- }
-
- int main()
- {
- int i;
- charArray str1(7);
- char* str2 = "string";
- for (i = 0; i < 7; i++)
- {
- str1[i] = str2[i];
- }
-
- for (i = 0; i < 7; i++)
- {
- cout << str1[i];
- }
- cout << str1.getLength() << endl;
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。