Reputation: 133
I have created the class and first constructor, but I don't know how to initialize 2d array to ref as asked in 2, need to do this using dynamic memory allocation.
Create a class named matrix having followed private members:
• int **p;
• int rows;
• int cols;
The class should have the following member functions:
MY CODE:
class Matrix
{
private:
int **p;
int rows;
int cols;
public:
// CONSTRUCTORS
Matrix()
{
rows = 2;
cols = 2;
p = new int*[2];
// initialize the array with 2x2 size
for (int i=0; i<2; i++)
{
p[i] = new int[2];
}
// taking input for the array
for (int i=0; i<2; i++)
{
for (int j=0; j<2; j++)
{
p[i][j] = 0;
}
}
};
Matrix(int **ref, int r, int c)
{
rows = r;
cols = c;
p = new int*[rows];
// initialize the array with 2x2 size
for (int i=0; i<rows; i++)
{
p[i] = new int[cols];
}
// taking input for the array
for (int i=0; i<rows; i++)
{
for (int j=0; j<cols; j++)
{
p[i][j] = **ref;
}
}
}
friend ostream& operator << (ostream& output, Matrix& obj)
{
output << obj.rows;
cout << " = ROWS" << endl;
output << obj.cols;
cout << " = columns" << endl;
for (int i=0; i<obj.rows; i++)
{
for(int j=0; j<obj.cols;j++)
{
cout << obj.p[i][j] << " " ;
}
cout << endl;
}
return output;
}
};
int main()
{
Matrix a;
cout << a << endl;
return 0;
}
Upvotes: 1
Views: 1180
Reputation: 75062
It seems p[i][j] = **ref;
should be p[i][j] = ref[i][j];
.
Also you should follow The Rule of Three. In other words, you should declare copy constructor and assignment operator to handle object (including pointers) copying properly.
Upvotes: 1