重载运算符[]
我有一个任务是在 C++ 中编写一个类矩阵,并且有一个条件,要覆盖矩阵的运算符 [],因此如果我有一个名为 Matrix 且带有“Matrix[0][0]”的矩阵,我必须首先使用它元素,在它的第一行。我用二维动态数组和模板(T **矩阵)表示矩阵。你能帮我一下吗?
PS:我用这个方法来创建二维数组:
template <class T>
T ** Matrix<T>::createMatrix(unsigned int rows, unsigned int cols)
{
T** matrix = new T*[rows];
for (unsigned int i = 0; i < rows; i++) {
matrix[i] = new T[cols];
}
return matrix;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您无法在 C++ 中本地执行此操作,但您可以简单地以这种方式实例化您的矩阵:
这样第一个 [ ] 返回另一个矩阵,该矩阵将返回您想要的项目。当然,对于您的类来说,更好的名称是 Vector,以及一个名为 Matrix 的包装类,它创建一个内部
Vector>
。You can't do that natively in C++, but you could simply instanciate your matrix this way:
This way the first [ ] returns another matrix which will return the item you want. Of course a much better name for your class then would be Vector, and a wrapper class called Matrix that creates an internal
Vector<Vector<T>>
.正如您的要求所述,您用来创建矩阵的方法与类没有任何关系。您正在创建一个简单的
T**
,在类方法中执行它并没有什么区别。创建可在
matrix[i][j]
中使用的T
矩阵意味着表达式matrix[i]
必须返回类型上还定义了运算符[]
返回T
。因此,通常的方法是将其分解为以下步骤:MatrixRow&
MatrixRow& operator[] (int)
返回一个T&
当从矩阵读取值时,还会使用这些运算符的
const
版本(非常量写入矩阵时将使用版本)。因此,至少,您应该创建一个具有此接口的类:
PS:这听起来像一个家庭作业问题,是吗?
The method you are using to create the matrix doesn't have anything to do with a class, as your requirements state. You are creating a simple
T**
, it doesn't make a difference that you are doing it in a class method.Creating a matrix of
T
that can be used as inmatrix[i][j]
means that the expressionmatrix[i]
must return a type on which operator[]
is also defined to return aT
. Therefore, the usual way to do it is break it down in steps:Matrix<T> operator[] (int)
returns aMatrixRow<T>&
MatrixRow<T>& operator[] (int)
returns aT&
There will also be
const
versions of these operators to be used when reading values from the matrix (non-const versions will be used when writing to the matrix).So, at the minimum, you should create a class with this interface:
PS: This reads like a homework question, is it one?
我假设矩阵是矩阵的 T** 类型的成员变量。
现在您可以编写类似于
访问第 42 行中的元素 1337 的内容。
i assume matrix is a member variable of type T** of Matrix.
Now you may write something like
to access element 1337 in row 42.
您可以通过两个课程来完成此操作。矩阵类重写 [] 并返回一个行对象。 row 对象覆盖 [] 并返回一个标量。
You can do this with two classes. The matrix class overrides [] and returns a row object. The row object overrides [] and returns a scalar.
您想要做的是在operator[]中返回一个T*,因为然后它可以将operator[]本机应用于它并获得您想要的结果。然而,我想指出的是,让你的指针保持原始状态是非常糟糕的做法。
What you want to do is return a T* in operator[], as it can then have operator[] applied to it natively and get the result that you want. However, I want to point out that it's pretty bad practice to leave your pointers raw.