重载下标操作符并使用双指针
Overloading subscript operator and working with double-pointers?
我需要使用以下变量,并且必须为赋值编写自己的包装器。我超越了赋值(因为我将不得不使用我制作的这个包装器),并希望重载包装器中的下标操作符,以便将其与双指针数组一起使用。我在代码中的意思是:
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
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 矢量下标超出SFML游戏中的范围
- 如何在C++程序中使用下标数字?
- 一组值的零开销下标运算符
- 运行时错误:矢量下标超出范围:正在检查空集
- 如何重载下标运算符 [] 以引用 2d STL 数组?
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 将类实例作为指针传递,并在此指针上使用过载的下标运算符
- 如何使用下标访问从函数作为指针返回的数组
- 重载下标运算符不返回指针
- 如何通过指针简化重载下标运算符的使用
- 错误 C2109:下标需要数组或指针类型 5
- 收到错误"二进制'[':"const typ"未定义此运算符"或"下标需要数组或指针类型
- 使用向量和指针的双下标重载的区别
- 指针映射的数组下标运算符
- 指向不完整类型'const std::complex的指针下标,<float>当使用C ++ 11时
- 在传递给函数的 char 指针上使用下标运算符不会修改值。为什么?
- 下标需要数组或指针类型
- 重载下标操作符并使用双指针