日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

C++中数组访问操作符的重载

發(fā)布時間:2025/4/5 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++中数组访问操作符的重载 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 1 C++中數(shù)組訪問操作符的重載
      • 1.1 重載數(shù)組訪問操作符
    • 2 重載數(shù)組訪問操作符時出現(xiàn)的問題

1 C++中數(shù)組訪問操作符的重載

1.1 重載數(shù)組訪問操作符

對于數(shù)組操作符:

  • 數(shù)組操作符是C/C++中的內(nèi)置操作符。
  • 數(shù)組訪問符的原生意義是數(shù)組訪問和指針運算。

數(shù)組訪問操作符([]):

  • 只能通過類的成員函數(shù)重載。
  • 重載函數(shù)能且僅能使用一個參數(shù)。
  • 可以定義不同參數(shù)的多個重載函數(shù)。

數(shù)組訪問符的重載能夠使得對象數(shù)組模擬數(shù)組的行為。

重載數(shù)組訪問操作符:

#include <iostream> #include <string>using namespace std;class Test {int a[5]; public:int& operator [] (int i){return a[i];}int& operator [] (const string& s){if( s == "1st" ){return a[0];}else if( s == "2nd" ){return a[1];}else if( s == "3rd" ){return a[2];}else if( s == "4th" ){return a[3];}else if( s == "5th" ){return a[4];}return a[0];}int length(){return 5;} };int main() {Test t;for(int i=0; i<t.length(); i++){t[i] = i;}for(int i=0; i<t.length(); i++){cout << t[i] << endl;}cout << t["5th"] << endl;cout << t["4th"] << endl;cout << t["3rd"] << endl;cout << t["2nd"] << endl;cout << t["1st"] << endl;return 0; }

2 重載數(shù)組訪問操作符時出現(xiàn)的問題

對于如下代碼在VS中和g++中都可以編譯通過,但是運行的時候就會出現(xiàn)由于訪問了0地址而出錯。

#include <iostream> #include <string>using namespace std;class Demo30 { private:int val[4]; public:Demo30(){val[0] = 0;val[1] = 1;val[2] = 2;val[3] = 3;}int operator [] (int index){if ((0 <= index) && (index < 4)){return val[index];}return -1;}int operator [] (string index) const // 這里返回值必須為int,否則無法復(fù)現(xiàn)錯誤{if (index == "0"){return val[0];}else if (index == "1"){return val[1];}else if (index == "2"){return val[2];}else if (index == "3"){return val[3];}else{return -1;}}};int main() {const Demo30 demo;cout << demo[0] << endl; //這里下標(biāo)必須為0,否則編譯錯誤return 0; }

這是編譯器的bug嗎?先把問題掛在這里。


參考資料:

  • C++深度解析教程
  • 總結(jié)

    以上是生活随笔為你收集整理的C++中数组访问操作符的重载的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。