【发布时间】:2021-07-19 13:54:10
【问题描述】:
我想重载“[]”女巫用于访问数组
但我也想分开读/写来做不同的事情
例如:
class myclass{
private:
int val;
public:
myclass(){val=0;}
myclass(int _in){val=_in;}
....
//for A=myclass[n]
myclass& operator[](int index){
...
return
}
//for myclass[n]=B
myclass& operator[](int index){
...
return
}
}
【问题讨论】:
-
您可能拥有不同于读/写版本的 const/non-const 版本。
-
这看起来可以通过返回代理来完成
-
问题是你不是在读/写
operator[],而是读/写结果。因此,您必须编写一个由operator[]返回的类,并在读取和写入时采取相应的行动。 -
假设您希望两个重载具有相同的参数类型(在您的情况下为
int)可以为const重载operator[]()(不能更改(非可变)成员myclass也不返回对myclass成员的非const引用)和非const(能够更改myclass的成员)。也可以为不同的参数类型重载operator[]()(例如,int和std::string,如果这样的用法对您的类有意义)。
标签: c++ operator-overloading overloading subscript array-indexing