重载下标操作符并使用双指针

Overloading subscript operator and working with double-pointers?

本文关键字:指针 下标 操作符 重载      更新时间:2023-10-16

我需要使用以下变量,并且必须为赋值编写自己的包装器。我超越了赋值(因为我将不得不使用我制作的这个包装器),并希望重载包装器中的下标操作符,以便将其与双指针数组一起使用。我在代码中的意思是:

What I have:

:

typedef struct {        // A pixel stores 3 bytes of data:
    byte red;       //  intensity of the red component
    byte green;     //  intensity of the green component
    byte blue;      //  intensity of the blue component
} pixel;
typedef struct { 
    int   rows, cols;   /* pic size */
    pixel **pixels;     /* image data */
} image;

我的类(当然包含在header中):

pixels& MyWrapper::operator[] (const int nIndex) {
    return Image.pixels[nIndex]; // where Image is of type image
}

当然这不会工作,因为双指针返回一个指针,这不是我告诉它返回的,但返回*pixels&也不返回。只是为了满足我的好奇心,并帮助我理解为什么这是不可能的,有人能告诉我这将如何实现,如果它可以,为什么是这样的?请记住,我还不是很了解指针(我知道它们是如何工作的基础知识,但仅此而已),我希望利用这一点来拓宽我的理解。

这是比较典型的,对于c++:

#include <vector>
namespace AA {
    class t_point {
    public:
        t_point(const size_t& X, const size_t& Y) : d_x(X), d_y(Y) {
        }
       const size_t& x() const { return this->d_x; }
        const size_t& y() const { return this->d_y; }
    private:   
        size_t d_x;
        size_t d_y;
    };
    class t_array {
    public:
        // abusive, but possible. prefer `at`
        const int& operator[](const t_point& idx) const {
            return this->at(idx.x(), idx.y());
        }
        const int& at(const t_point& idx) const {
            return this->at(idx.x(), idx.y());
        }
        const int& at(const size_t& x, const size_t& y) const {
            return this->d_objects[x][y];
        }
    private:
        // or use your c image representation...
        std::vector<std::vector<int> > d_objects;
    private:
        static const int& ctest(const t_array& arr) {
            const t_point pt(1, 2);
            return arr[pt];
            return arr.at(pt);
            return arr.at(pt.d_x, pt.d_y);
        }
    };
}

在这种情况下使用一个索引的最大问题是不清楚您试图访问哪个索引(像素),同时将所有坐标计算推给客户端。如果它是一个单指针,您仍然会将问题推给客户端,但您可以预测地访问索引。

双…内存中的布局可以变化,但不一定是连续的。将其发布为单个值(逻辑上,作为1D数组)而不是2D数组或点(例如)是一个糟糕的设计。

一开始就不清楚为什么要使用双间接。

如果pixels是指向像素数组的双指针,则可以执行

pixels& MyWrapper::operator[] (const int nIndex) {
    return (*Image.pixels)[nIndex]; // where Image is of type image
}

如果pixels是指向数组指针的数组指针,则需要两个下标:

pixels& MyWrapper::operator() ( int xIndex, int yIndex ) {
    return Image.pixels[yIndex][xIndex]; // where Image is of type image
}

这里发生了一些奇怪的事情。

  • typedef class { } identifier是不好的c++。使用class identifier { };,否则该类没有名称,因此您不能在class { }作用域之外定义成员函数。(在其他问题中)
  • 没有理由将参数类型设置为const int。纯int完成同样的事情。
  • 没有明显的双重间接原因。通常在c++中,我们避免直接使用指针。可能有一个预先打包的标准结构可以代替。

使用boost:: multi_array