是否可以在像“int & operator[]”这样的重载中使用修改后的返回引用?
Is it possible to use the modified returned reference in an overload like `int &operator[]'?
假设我有一个 class 实现了一个按需增长的 int
数组。 class 还实现了 int &operator[]
方法重载 []
运算符并返回对数组中值的引用。
现在我像这样在循环中使用运算符
classInstance[index] += 1;
我想知道是否可以在int &operator[]
函数中使用增量值?
为了说清楚,我想要的是能够知道引用整数的新值是什么,以便更新最大值和最小值。
解决这个问题的方法是 return 一些 假装 是 int&
的东西,同时它本身为 [= 等方法提供重载12=],等等
像这样:
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]};
}
显然,这只是一段粗略的代码,但我认为它可以被提炼成相当不错的东西。
你可以使用 Execute-Around Pointer idiom 。您的 operator[]
需要 return 实现必要操作的 class 的代理对象。然后,您可以 "do something" 在代理对象的析构函数中或在其实现中的操作之后立即执行。
假设我有一个 class 实现了一个按需增长的 int
数组。 class 还实现了 int &operator[]
方法重载 []
运算符并返回对数组中值的引用。
现在我像这样在循环中使用运算符
classInstance[index] += 1;
我想知道是否可以在int &operator[]
函数中使用增量值?
为了说清楚,我想要的是能够知道引用整数的新值是什么,以便更新最大值和最小值。
解决这个问题的方法是 return 一些 假装 是 int&
的东西,同时它本身为 [= 等方法提供重载12=],等等
像这样:
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]};
}
显然,这只是一段粗略的代码,但我认为它可以被提炼成相当不错的东西。
你可以使用 Execute-Around Pointer idiom 。您的 operator[]
需要 return 实现必要操作的 class 的代理对象。然后,您可以 "do something" 在代理对象的析构函数中或在其实现中的操作之后立即执行。