【问题标题】:Overloading subscript operators for specific read and write operations [duplicate]为特定的读写操作重载下标运算符[重复]
【发布时间】: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&amp; operator[] (K key) const; 代替V operator[] (K key) const; 怎么样
  • 这是同一个问题,但它没有帮助,因为仍然只访问写入
  • 这是同一个问题,但它没有帮助,因为只有写仍然被访问你的意思是你改变后写仍然被访问你的V operator[] (K key) const; //Readconst V&amp; operator[] (K key) const; //Read

标签: c++ overloading subscript


【解决方案1】:

重载是根据参数的静态类型完成的。如果对象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); }
     // ...
 };
猜你喜欢
  • 2012-06-21
  • 2014-04-19
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-08
相关资源
最近更新 更多