![](/img/trans.png)
[英]distinguish between read and write using operator [] overloading in c++
[英]C++: Overloading the [ ] operator for read and write access
通常,如何為讀取和寫入訪問聲明類的index [ ]
運算符?
我試過類似的東西
/**
* Read index operator.
*/
T& operator[](T u);
/**
* Write index operator
*/
const T& operator[](T u);
這給了我錯誤
../src/Class.h:44:14: error: 'const T& Class::operator[](T)' cannot be overloaded
../src/Class.h:39:8: error: with 'T& Class::operator[](T)'
你的可變版本很好:
T& operator[](T u);
但const
版本應該是一個const
成員函數,並返回一個const
引用:
const T& operator[](T u) const;
^^^^^
這不僅可以將其與其他重載區分開來,還允許(只讀)訪問類的const
實例。 通常,重載的成員函數可以通過它們的參數類型和const / volatile資格來區分,但不能通過它們的返回類型來區分。
您只需要一個可用於讀取和寫入的重載:
T& operator[](int);
話雖如此,您可能還希望有一個const
重載:
const T& operator[](int) const;
這將為您的類的const
實例提供只讀索引。
您收到錯誤,因為重載的函數不能只返回類型。 但它們可以因常數不同而不同。
/**
* Write index operator.
*/
T& operator[](T u);
/**
* Read index operator
*/
const T& operator[](T u) const;
注意“寫”和“讀”交換的地方。
另外,難道你不是真的意味着運算符的參數是某種整數類型嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.