I'm new to C++, and it's my first year in computer science and... I just want to ask if... is there a way to make what i put in the title work?...
To further explain what I mean, here is an example:
template <class dataType>
class squareMatrix{
private:
int size_side;
dataType *mainPtr;
public:
squareMatrix(int n){
this->size_side = n;
mainPtr = new dataType[n*n];
}
void index(int row, int column, dataType value){
mainPtr[row+(size_side*column)] = value;
}
};
so as you can see I need to use this method to manipulate an index in the matrix
squareMatrix<int> obj(2); // created a matrix of 2x2 size
obj.index(0,0,10); // here is the method to store the number 10 in the 0,0 index
And then my question, is there a way to make this into this?
obj.index(0,0) = 10;
Instead putting an extra parameter to the method is there a way to use the "=" or the assignment operator instead?
Yes, you can make index
returning the reference to element, (like how std::vector::operator[]
and std::vector::at
do,) e.g.
dataType& index(int row, int column) {
return mainPtr[row+(size_side*column)];
}
then you can assign to the return value like
obj.index(0,0) = 10;