在C ++中重载数组索引运算符[]
运算符重载在面向对象的编程语言功能中具有重要作用。运算符重载是一种编译时或静态多态性。
算法
Begin Create a class Arr and declare size of array. Inside the class, initialize all the elements by using for loop. Print the all elements. End.
范例程式码
#include <iostream>
#include <stdlib.h>
using namespace std;
const int M = 7;
class Arr {
private:
int A[M];
int size;
public:
Arr(int s, int v) {
if(s>M) {
cout<<endl<<"This is beyond maximum size";
exit(1);
}
size = s;
for(int i=0;i<size;i++)
A[i] = v;
}
int& operator[](int i) {
if( (i<0) || (i>=size) ) {
cout<<endl<<"Error: Array out of bound";
exit(1);
}
return A[i];
}
};
int main() {
int i=0;
Arr a(7,0);
for(i=0;i<7;i++)
a[i] = i*10;
cout<<"数组元素是:"<<endl;
for(i=0;i<7;i++) {
int val = a[i];
cout<<val<<endl;
}
return 0;
}输出结果
数组元素是: 0 10 20 30 40 50 60
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短