CArray::operator [ ] 的兩個版本

from MSDN:

 

CArray::operator [ ]

TYPE& operator []( int nIndex );

TYPE operator []( int nIndex ) const;

 

Remarks

The first operator, called for arrays that are not const, may be used on either the right (r-value) or the left (l-value) of an assignment statement. The second, called forconst arrays, may be used only on the right.

 

第一個版本,不被const修飾,可以是左值調用也可以是右值調用。(調用者不能是const對象,只能是非const對象)

第二個版本,被const修飾,只能是右值調用。(調用者可以是const對象也可以是非const對象,但是有了第一個版本,只被const對象調用)

 

例如:

    int it = 0;
    CArray<int, int&> ca;
    ca.Add(it);
    int iTest = ca[0];    // 調用第一個版本
    const CArray<int, int&>& p = ca;
    iTest = p[0];      // 調用第二個版本


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章