I've problem with Initialize the element of multidimensional array.
Here's my code:
class A{
int *const e;
const int row, column;
public:
A::A(int r, int c) : row(r), column(c), e(new int[r*c])
{
for (int i = 0; i < r*c; i++)
{
e[i] = 0;
}
}
A(const A &matrix) : row(matrix.row), column(matrix.column) ,e(new int[matrix.row*matrix.column])
{
for (int i = 0; i < matrix.row*matrix.column; i++)
{
e[i] = matrix.e[i];
}
}
virtual ~A() //destructing a A
{
delete[] e;
}
};
But when I'm trying Initialize the element of multidimensional array I've got a error:
int main(int argc, char* argv[])
{
A c(2, 5);
c[0][0] = 1;
A a(c);
return 0;
}
1 IntelliSense: no operator "[]" matches these operands operand types are: MAT [ int ]
Edit: According to comments I try to write operator []
virtual int *const operator[ ](int r)
{
return e[r][0];
}
It should get first element of the r row. But I've got a error:
1 IntelliSense: expression must have pointer-to-object type
You're trying to apply the []
to the class A, C++ only knows how to use the operator []
on arrays. In order to use them for A you have to tell how []
works for A, so inside your class definition you should put:
int *operator[](int x){
return &e[x*row];
}
It basically receives the number you have put between brackets, and returns the corresponding row(an array), so you can apply []
again easily, so for example:
c[0]
returns the first row
c[0][1]
access the second element of the first row
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.