是否可以在像`int& operator []'这样的重载中使用修改后的返回引用?

时间:2015-07-05 13:35:35

标签: c++ operator-overloading

假设我有一个实现int数组的类,该数组按需增长。该类还实现了int &operator[]方法重载[]运算符并返回对数组中值的引用。

现在我在这样的循环中使用运算符

classInstance[index] += 1;

我想知道是否可以在int &operator[]函数中使用递增的值?

为了说清楚,我想要的是能够知道引用的整数的新值是什么,以便更新最大值和最小值。

2 个答案:

答案 0 :(得分:3)

解决此问题的方法是返回假装int&的内容,同时为operator+=等方法提供重载。

这样的事情:

class MyIntReference {
 public:
  MyIntReference(int& reference_to_wrap) :
    wrapped_reference_{reference_to_wrap}
  {}

  // this method returns void, but you could have it return whatever you want
  void operator+=(const int addend) {
    wrapped_reference_ += addend;
    DoWhateverYouWant();
  }

 private:
  int& wrapped_reference_;
}

// then, in your other class
MyIntReference YourOtherClass::operator[](const int index) {
  return MyIntReference{my_array_[index]};
}

显然,这只是一段粗略的代码,但我认为它可以被提炼成非常好的东西。

答案 1 :(得分:1)

您可以使用Execute-Around Pointer idiom。您的operator[]需要返回实现必要操作的类的代理对象。然后你可以做一些事情"在代理对象的析构函数中或在其实现中的操作之后立即。

相关问题