【c++ 重载】

重载"[]":

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 struct Node{
 5     #define N 1000
 6     int data[N], cnt;
 7     string s[N];
 8     Node(int c = 0):cnt(c){}
 9     int &operator[](string str) {
10         for(int i = 1; i <= cnt; i++) {
11             if(s[i] == str) {
12                 return data[i];
13             }
14         }
15         data[++cnt] = 0;
16         s[cnt] = str;
17         return data[cnt];
18     }
19 };
20 int main()
21 {
22     Node a;
23     a["abc"] = 1;
24     a["ab"] = 2;
25     cout<< a["a"] <<endl<< a["ab"]<< endl<< a["abc"]<< endl;
26 }
27 //结果:
28 //0
29 //2
30 //1
View Code

 

posted @ 2014-09-28 21:16  jklongint  阅读(120)  评论(0编辑  收藏  举报