C++下標(biāo)運算符詳解
C++ 規(guī)定,下標(biāo)運算符[ ]
必須以成員函數(shù)的形式進(jìn)行重載。該重載函數(shù)在類中的聲明格式如下:
返回值類型 & operator[ ] (參數(shù));
const 返回值類型 & operator[ ] (參數(shù)) const;
使用第一種聲明方式,[ ]
不僅可以訪問元素,還可以修改元素。使用第二種聲明方式,[ ]
只能訪問而不能修改元素。在實際開發(fā)中,我們應(yīng)該同時提供以上兩種形式,這樣做是為了適應(yīng) const 對象,因為通過 const 對象只能調(diào)用 const 成員函數(shù),如果不提供第二種形式,那么將無法訪問 const 對象的任何元素。下面我們通過一個具體的例子來演示如何重載[ ]
。我們知道,有些較老的編譯器不支持變長數(shù)組,例如 VC6.0、VS2010 等,這有時候會給編程帶來不便,下面我們通過自定義的 Array 類來實現(xiàn)變長數(shù)組。
#include <iostream> using namespace std; class Array{ public: Array(int length = 0); ~Array(); public: int & operator[](int i); const int & operator[](int i) const; public: int length() const { return m_length; } void display() const; private: int m_length; //數(shù)組長度 int *m_p; //指向數(shù)組內(nèi)存的指針 }; Array::Array(int length): m_length(length){ if(length == 0){ m_p = NULL; }else{ m_p = new int[length]; } } Array::~Array(){ delete[] m_p; } int& Array::operator[](int i){ return m_p[i]; } const int & Array::operator[](int i) const{ return m_p[i]; } void Array::display() const{ for(int i = 0; i < m_length; i++){ if(i == m_length - 1){ cout<<m_p[i]<<endl; }else{ cout<<m_p[i]<<", "; } } } int main(){ int n; cin>>n; Array A(n); for(int i = 0, len = A.length(); i < len; i++){ A[i] = i * 5; } A.display(); const Array B(n); cout<<B[n-1]<<endl; //訪問最后一個元素 return 0; }
運行結(jié)果:
5↙
0, 5, 10, 15, 20
33685536
重載[ ]
運算符以后,表達(dá)式arr[i]
會被轉(zhuǎn)換為:
需要說明的是,B 是 const 對象,如果 Array 類沒有提供 const 版本的operator[ ]
,那么第 60 行代碼將報錯。雖然第 60 行代碼只是讀取對象的數(shù)據(jù),并沒有試圖修改對象,但是它調(diào)用了非 const 版本的operator[ ]
,編譯器不管實際上有沒有修改對象,只要是調(diào)用了非 const 的成員函數(shù),編譯器就認(rèn)為會修改對象(至少有這種風(fēng)險)。
到此這篇關(guān)于C++下標(biāo)運算符詳解的文章就介紹到這了,更多相關(guān)C++下標(biāo)運算符內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
c++11 符號修飾與函數(shù)簽名、函數(shù)指針、匿名函數(shù)、仿函數(shù)、std::function與std::bind
這篇文章主要介紹了c++11 符號修飾與函數(shù)簽名、函數(shù)指針、匿名函數(shù)、仿函數(shù)、std::function與std::bind,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05關(guān)于C++中的友元函數(shù)的一些總結(jié)
以下是對C++中的友元函數(shù)進(jìn)行了詳細(xì)的總結(jié)介紹,需要的朋友可以過來參考下2013-09-09