C++下标 [] 运算符重载

C++ subscript [] operator overloading

本文关键字:运算符 重载 下标 C++      更新时间:2023-10-16

对不起,格式,我从来没有真正发布过这样的论坛,所以我必须学习如何做。

我的问题是:我正在编写一个模板类,我想通过多种[]运算符访问我的容器。我在这个主题上读了一些书,所以我已经能够重载一个,但我还需要更多:

所以在我的头文件中,关于我的容器的相关内容:

template <class T>
class version_controlled_vector
{
    int rev;                                         
    bool vector_state_changed;
    std::vector< std::string > revision;     
    std::vector< std::vector<T> > v;                 

    //first one works ok, im satisfied with it:
    std::vector<T>& operator[] (const int idx)
    {
        return v[idx];
    }
    //im not sure how to define the further one(s?):
    T& operator[](const int idx2) const
    {
        return v[idx2];
    }
    //...and ofc some other code
};
/

/在我的主要.cpp有这些用法:

version_controlled_vector<int> mi;
version_controlled_vector<std::string> ms;
//this works, and i d like to keep it,
5 == mi[ 0 ][ 0 ];
//and i d like to have these two usages too:
//getting the first character of the stored string:
'H' == ms[ 0 ][ 0 ];    // with the first overload from the header ms[0][0][0]    
works  to get the first character of the string for eg "Hello" 
but, i have to use  the ms[0][0] format to achieve this
//and this:
4 == mi[ 0 ]; // i d like this as if it d behave like 4 == mi[0][0];

我真的不明白当我重载使用[][]时如何使用single[]

读到的唯一解决方案可能是 const-重载,但我完全不确定,我是一个相当弱的人。

感谢您的想法!

我认为你正在混淆类的界面。班级的期望是:

  1. 从第 j 个版本中获取第 i 个值。
  2. 从最新版本获取第 i 个值。
  3. 获取第 j 版本。

您可以选择使用重载的operator[]函数来获取这些值,但最好具有反映接口的函数。

// Get the versionIndex-th version.
std::vector<T>& getVersion(int versionIndex);
// Get the itemIndex-th value from the versionIndex-th version.
T& getItem(int versionIndex, int itemIndex);
// Get the itemIndex-th value from the latest version.
T& getItem(int itemIndex);

然后,实现将更简单且不那么混乱。

std::vector<T>& getVersion(int versionIndex)
{
    // Make sure to add out of bound checks
   return v[versinIndex];
}
T& getItem(int versionIndex, int itemIndex)
{
    // Make sure to add out of bound checks
   return v[versinIndex][itemIndex];
}
T& getItem(int itemIndex);
{
    // Make sure to add out of bound checks
   return v.back()[itemIndex];
}

鉴于这些,至少对我来说,唯一有意义的operator[]是从最新版本返回第 i 个值。

T& operator[](int itemIndex);
{
    // Make sure to add out of bound checks
   return v.back()[itemIndex];
}

这有点棘手,当你写作时,你需要意识到这一点

version_controlled_vector<int> mi;
5 == mi[0][0];

在第二次获取期间,您不再访问version_controlled_vector类,但它的内部属性及其类型是std::vector<T>,它有自己的下标运算符,您可以在第二个[0]中调用。

要控制第二次获取的下标运算符,您需要创建另一个派生自 std::vector<T> 并具有重载下标运算符的类。然后你应该在version_controlled_vector的实现中使用这个类而不是std::vector