我目前正在尝试为读取和写入操作重载“[]”运算符。我创建它们如下所示:
V operator[] (K key) const; //Read
V& operator[] (K key); //Write
但是,只有“write”被以下两个调用:
foo["test"] = "bar"; //Correct, will use 'write'
cout << foo["test"]; //Incorrect, will use 'write'
这是什么原因,是否有可能的解决方案?
同样的问题没有帮助,在这里找到:C++: Overloading the [ ] operator for read and write access
虽然,提出的解决方案没有按预期工作,仍然只访问了写重载。
重载是根据参数的静态类型完成的。如果您使用运算符的对象 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); }
// ...
};