为特定的读写操作重载下标运算符
Overloading subscript operators for specific read and write operations
我当前正试图为读取和写入操作重载"[]"运算符。我创建了它们,如下所示:
V operator[] (K key) const; //Read
V& operator[] (K key); //Write
然而,只有"写入"从以下两个调用:
foo["test"] = "bar"; //Correct, will use 'write'
cout << foo["test"]; //Incorrect, will use 'write'
造成这种情况的原因是什么?有可能的解决方案吗?
同样的问题没有帮助,可以在这里找到:C++:重载[ ;] ;读写访问的操作员
尽管如此,所提供的解决方案并没有按预期工作,而且仍然只访问了写过载。
重载是基于参数的静态类型完成的。如果使用运算符的对象foo
是非const
,则使用非const
重载。如果是const
,则使用const
过载。
如果你想区分阅读和写作,你需要从下标运算符返回一个代理,它可以转换为适合阅读的类型,并具有适合写作的赋值运算符:
class X;
class Proxy {
X* object;
Key key;
public:
Proxy(X* object, Key key): object(object), key(key) {}
operator V() const { return object->read(key); }
void operator=(V const& v) { object->write(key, v); }
};
class X {
// ...
public:
V read(key) const;
void write(key, V const& v);
Proxy operator[](Key key) { return Proxy(this, key); }
V operator[](Key key) const { return this->read(key); }
// ...
};
相关文章:
- 如何重载下标运算符 [] 以引用 2d STL 数组?
- 允许 nullptr 的 C++ 重载下标取消引用
- 基成员的重载下标运算符
- 如何重载下标运算符以返回可以是左值的可选值?
- 重载下标运算符不返回指针
- 如何通过指针简化重载下标运算符的使用
- 将 boost::shared_ptr 与重载下标运算符 ([]) 的类一起使用
- 重载下标运算符以根据分配的类型调用函数
- 重载下标运算符会导致访问冲突
- 如果不满足"if criteria",默认返回什么?重载下标运算符
- 为特定的读写操作重载下标运算符
- C++:重载下标运算符(不同的返回类型)
- 毁灭战士 3 来源:为什么表示 2 向量的类会重载下标运算符两次
- 通过重载下标操作符()从矩阵中获取向量
- 重载下标操作符
- 在模板双链表类中重载下标操作符
- 如何重载下标操作符以允许RPG字符数组
- 使用重载下标运算符"[ ]"获取数组并将其设置为数组的值将不起作用
- c++两个版本的重载下标操作符
- 重载下标操作符并使用双指针