为特定的读写操作重载下标运算符

时间:2015-11-11 00:09:16

标签: c++ overloading subscript

我目前正试图超载' []'读写操作的运算符。我创建了它们如下:

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++: Overloading the [ ] operator for read and write access

虽然,所提出的解决方案没有按预期工作,但仍然只访问了写入重载。

1 个答案:

答案 0 :(得分:4)

根据参数的静态类型完成重载。如果您使用运算符的对象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); }
     // ...
 };