下标运算符重载

下标运算符重载
1、下标运算符的含义
下标运算符是一个二元运算符,a[x]相当于a.operator[](x),b[x][y]相当于(b.operator[ ](x)).operator[ ](y)。
下标运算符“[ ]”的重载函数原型具有如下形式:
  type1& operator[ ](type2);
  其中,type1为数组类型,type2为下标类型。
说明:C++预定义对type1没有限制,但要求type2必须是int型,数组需要先声明后使用,若type2是其它类型,就需要对下标运算符重载。

 

2、下标运算符重载
除了type2是其它类型需要对下标运算符重载外,非数组类型的对象使用下标运算符时,也要对下标运算符重载。
对下标运算符重载只能使用成员函数,形式如下:
类型 类名::operator[ ](下标类型形参)
{
    函数体
}

 

例 建立联想数组(associative array)。
建立如下电话号码簿:
zhang    7075461
li       4047658
tan      2595121
cai      7732435

电话号码类:
class item{
  char *name;
  long  telnum;
};


item tel[4];


有了上述定义后,可以用tel[0],tel[1],tel[2]和tel[3]来分别表示四个人的姓名及电话,tel[0]表示zhang及电话7075461。但如果用tel[zhang]= 7075461,tel[li]= 4047658来表示一个人的姓名及电话,岂不是更方便?
由于zhang,li等不是系统规定的int型,要想用上面的表示方法,就必须对下标运算符进行重载。


 

#include <iostream.h>
#include <string.h>

class Assc_array
{ struct Item
  { char *name;
    long tel_num;
  };
  Item *table;
  int max;
  int items;
  public:
    Assc_array(int);
    long & operator[](char *);
    void printAll();
};

Assc_array::Assc_array(int nm=0)
{ max=nm;
  items=0;
  table=new Item[max];
}

long & Assc_array::operator[](char *nm)
{ Item *pi;
  for (pi=table;pi<table+items;pi++)
    if (strcmp(pi->name,nm)==0)
      return pi->tel_num;
  pi=table+items++;
  pi->name=new char[strlen(nm)+1];
  strcpy(pi->name,nm);
  pi->tel_num=0;
  return pi->tel_num;
}

void Assc_array::printAll()
{ for (int i=0;i<items;i++)
    cout<<table[i].name<<":"<<table[i].tel_num<<endl;
}

void main()
{ Assc_array tel_num_table(10);

  tel_num_table["zhang"]=7075461;
  tel_num_table["li"]=4047658;
  tel_num_table["tan"]=2595121;
  tel_num_table["cai"]=7732435;

  cout<<"zhang->"<<tel_num_table["zhang"]<<endl;
  cout<<"li->"<<tel_num_table["li"]<<endl;
  cout<<"tan->"<<tel_num_table["tan"]<<endl;
  cout<<"cai->"<<tel_num_table["cai"]<<endl;

  tel_num_table.printAll();
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值