Write two add() functions for the matrix class: one as a friend nonmember
function and one as a member function. Then explain the advantages of defining one over the other.
Both functions should accept two matrices and return a new matrix where each element is the sum of the corresponding elements of the two inputs.
friend matrix add(const matrix& m1, const matrix& m2);
matrix matrix::add(const matrix& m);
Use the following class definition and constructors/destructor as your base context:
class matrix {
public:
matrix(int d);
matrix(int d1, int d2);
~matrix();
int ub1() const { return (s1 - 1); }
int ub2() const { return (s2 - 1); }
private:
int** p;
int s1, s2;
};
matrix::matrix(int d): s1(d), s2(d){
if (d < 1) {
// cerr is the standard stream for error output
// similar to stderr in C
cerr << "illegal matrix size"
<< d << "by" << d << "\n";
exit(1);
}
p = new int*[s1];
for (int i = 0; i < s1; i++)
p[i] = new int[s2];
}
matrix::matrix(int d1, int d2): s1(d1), s2(d2){
if (d1 < 1 || d2 < 1) {
cerr << "illegal matrix size"
<< d1 << "by" << d2 << "\n";
exit(1);
}
p = new int*[s1];
for (int i = 0; i < s1; i++)
p[i] = new int[s2];
}
matrix::~matrix(){
for (int i = 0; i <= ub1(); ++i)
delete p[i];
delete []p;
}
The complete matrix code is also available in matrix.cpp inside the course download on the Resources page.
Paste (1) your two add() implementations and (2) your discussion below, then click Submit.
Your submission will take you directly to the results page, where your content will be displayed for review.