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

标签 c++ overloading subscript

<分区>

我目前正在尝试为读取和写入操作重载“[]”运算符。我创建它们如下所示:

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); }
     // ...
 };

关于c++ - 为特定的读写操作重载下标运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33642050/

相关文章:

c++ - 我们什么时候需要在#undef 之前使用#ifdef?

c++ - 如何检查是否转换为 wchar_t "failed"

c++ - 如何通过Windows Defender SmartScreen保护?

python - C++ 中用户定义类的动态分配,都具有相同的公共(public)函数

c++ - 简单的 C++ 运算符重载帮助

c++ - 表达式 : string subscript out of range. 属性传递问题?

c++ - 公共(public)全局变量或 get() 和 set() 方法?

c++ - 重载下标运算符未按预期工作

ios - 读取字典元素的预期方法在 "class"类型的对象上找不到

f# - 非惯用的全局运算符重载如何工作?