https://blog.csdn.net/qq_29344757/article/details/76855218
格式:
返回類型& operator[] (輸入參數列表);
注意返回的是引用;
重載操作符的原則是不能改變操作符的原有語義和操作數的個數;
”[]”用於取元素的值,且只有一個操作數,為括號內的值,這個是不可被改變的,但是括號內的值是針對該數組而操作的,所以”[]”操作符肯定有一個數組對象,這也就決定了對”[]”的重載實現的函數只能是類的成員函數,因為類的成員函數具有this指針,它可以指向對象本身(對象可以內含一個數組嘛):類必須得有一個數組成員?
因為返回的是引用,所以必然對象內部已經有存在的數組列表,鏈表也行,可以引用就行!
class cls { private: int ar[6]; public: cls(); int& operator[] (int i); //重載"[]"操作符 }; cls::cls() { int i; for (i = 0; i < 6; i++) { ar[i] = i + 1; } } int& cls::operator[] (int i) //返回引用,這樣才可以對返回值賦值 { return ar[i]; } int main(void) { cls c; printf("c[1] = %d\n", c[1]); c[4] = 16; printf("c[4] = %d\n", c[4]); return 0; }
”[]”內的操作數支持字符串類型;
class cls
{
private: int ar[6];
public:
int& operator[] (int i); //重載"[]"操作符,"[]"內的操作數的操作數是int類型
int& operator[] (const char* str); //重載"[]"操作符,"[]"內的操作數是字符串類型
};
int& cls::operator[] (const char* str)
{
//1st 2nd 3rd 4th 5th
if (!strcmp("1st", str))
return ar[0];
if (!strcmp("2nd", str))
return ar[1];
}
int main(void)
{
cls c;
printf("c[\"5th\"] = %d\n", c["1th"]);
c["2nd"] = 66;
printf("c[\"2nd\"] = %d\n", c["2nd"]);
return 0;
}