重载"[]":
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
时间: 2024-10-10 13:56:39