C++下标 [] 运算符重载
C++ subscript [] operator overloading
对不起,格式,我从来没有真正发布过这样的论坛,所以我必须学习如何做。
我的问题是:我正在编写一个模板类,我想通过多种[]
运算符访问我的容器。我在这个主题上读了一些书,所以我已经能够重载一个,但我还需要更多:
所以在我的头文件中,关于我的容器的相关内容:
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-重载,但我完全不确定,我是一个相当弱的人。
感谢您的想法!
我认为你正在混淆类的界面。班级的期望是:
- 从第 j 个版本中获取第 i 个值。
- 从最新版本获取第 i 个值。
- 获取第 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
。
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板