我的重载 [] 运算符不适用于伪 3D 数组

My overloaded [] operator does not work for a pseudo 3D array

本文关键字:适用于 3D 数组 不适用 运算符 重载 我的      更新时间:2023-10-16

我写了一个小演示,它应该实现三维std::vector的伪[][][] operator。目的是调用[] operator,直到只返回类型 T。不幸的是,程序似乎崩溃了,运算符被递归调用。

#include <vector>
#include <iostream>
template <class T>
class V1D : public std::vector<T>
{
private:
  int _iX = 0;
  int _iBeg = 0;
public:
  V1D(int x, int beg, std::vector<T> &buf)
    : _iX(x)
  {
    this->swap(buf);
    _iBeg = beg;
  }
  T& operator[] (int id) {
    return (*this)[id + _iBeg];
  }
};
template <class T>
class V2D : public std::vector<T>
{
private:
  int _iX = 0;
  int _iY = 0;
  int _iBeg = 0;
public:
  V2D(int x, int y)
    : _iX(x)
    , _iY(y)
  {
    this->resize(_iX*_iY);
  }
  V2D(int x, int y, int beg, std::vector<T> &buf)
    : _iX(x)
    , _iY(y)
  {
    this->swap(buf);
    _iBeg = beg;
  }
  V1D<T> operator[] (int id) {
    int iBeg = id*_iX;
    return V1D<T>(_iX, iBeg+_iBeg, *this);
  }
};
template <class T>
class V3D : public std::vector<T>
{
private:
  int _iX = 0;
  int _iY = 0;
  int _iZ = 0;
public:
  V3D() = default;
  V3D(int x, int y, int z) 
    : _iX(x)
    , _iY(y)
    , _iZ(z) 
  {
    this->resize(_iX*_iY*_iZ);
  }
  V2D<T> operator[] (int id) {
    int iBeg = id*_iY*_iZ;
    return V2D<T>(_iY, _iZ, iBeg, *this);
  }
};
int main()
{
    V3D<float> v3(3, 3, 3);
    float v = v3[1][1][0];
    v3[1][1][0] = 5;
    v = v3[1][1][0];
    std::cout << v << std::endl;
}

我不认为在 V1D 和 V2D 构造函数(可能应该是私有的)中这样做>swap(buf) 是一个好主意。如果你考虑一下,V3D::operator[] 将临时(它作为结果返回)中的空向量与变量中的任何内容交换。所以你失去了内容。这种设计将不起作用。您可能需要返回一个指针,指向包装在帮助程序类中的 vector 数据。

V1D 和 V2D 不应该也不需要保持/成为载体。它们应该包裹普通的 T 指针,可能带有内部尺寸。

你递

归地调用operator[]

T& operator[] (int id) {
    return (*this)[id + _iBeg];
}

应该是

T& operator[] (int id) {
    return std::vector<T>::operator[](id + _iBeg);
}