【发布时间】:2015-11-11 08:20:16
【问题描述】:
我目前正在尝试为读写操作重载“[]”运算符。我创建了它们,如下所示:
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
尽管提出的解决方案没有按预期工作,但仍然只访问了写入重载。
【问题讨论】:
-
为什么其他问题没有帮助?对我来说似乎是完全相同的问题。
-
用
const V& operator[] (K key) const;代替V operator[] (K key) const;怎么样 -
这是同一个问题,但它没有帮助,因为仍然只访问写入
-
这是同一个问题,但它没有帮助,因为只有写仍然被访问你的意思是你改变后写仍然被访问你的
V operator[] (K key) const; //Read到const V& operator[] (K key) const; //Read?
标签: c++ overloading subscript