AAA*_*AAA 2 c++ operator-overloading
我有一个模拟数组的 C++ 类,为了操作其成员,我实现了两个函数:set(size_t index, size_t value)和get(size_t index)。我想重载 [] 运算符以具有以下功能:
MyCustomArray[index] = value //->set(size_t index, size_t value)
Run Code Online (Sandbox Code Playgroud)
和
value = MyCustomArray[index] //->get(size_t index)
Run Code Online (Sandbox Code Playgroud)
get可以通过重载轻松实现,但我不知道如何实现set,因为我事先需要参数value。
我的类是固定字数组的实现(数组中的元素最多有 P 位,其中 P 是一个参数,它可以小于常规机器字)。为了支持此功能,set并get操作常规 C/C++ 数组中值的一系列位。
在这种情况下是否可以超载?
提前致谢!
这就像 std::vector::operator[] 所做的那样 - 使用代理对象。
class MyCustomArray
{
public:
using value_type = unsigned;
class Proxy
{
public:
friend class MyCustomArray;
operator value_type() const
{
return m_customArray.get(m_index);
}
Proxy & operator=(value_type value)
{
m_customArray.set(m_index, value);
return *this;
}
private:
Proxy(MyCustomArray & customArray, size_t index)
: m_customArray(customArray), m_index(index) {}
MyCustomArray & m_customArray;
size_t m_index;
};
value_type operator[](size_t index) const
{
return get(index);
}
Proxy operator[](size_t index)
{
return Proxy(*this, index);
}
value_type get(size_t index) const;
void set(size_t index, value_type value);
private:
/// The data goes here
};
Run Code Online (Sandbox Code Playgroud)
然后
void work(MyCustomArray & arr)
{
// Return a Proxy object, and call operator= over it.
arr[3] = 5;
// arr_2 is of type MyCustomArray::Proxy
auto arr_2 = arr[2];
arr_2 = 1; // modifies arr[2]
unsigned x = arr_2; // gets 1 from arr[2]
// This works, due to auto conversion to value_type:
std::cout << arr_2 << '\n';
}
Run Code Online (Sandbox Code Playgroud)