operation overloading in c++ You should also support stream insertion (similar t
ID: 670352 • Letter: O
Question
operation overloading in c++
You should also support stream insertion (similar to overriding the toString method in Java) so that your matrices can easily be printed.
cout << a << endl;
// example output: [ 1, 2 ]
// [ 1, 3 ]
You should also support matrix assignment using an initializer list (to easily overwrite existing elements) that looks like the following:
Matrix d(2, 2);
d = {{ 1, 2 },
{ 3, 4 }};
In order to support this last operator overload (i.e., matrix assignment using an initializer list), you will need to use a standard template library (STL) class called std::initializer list. The type signature for the << parameter representing the list should be std::initializer list> or simply i list if you use the provided typedef. It is preferred that you specify the parameter as a const i list & in order to avoid any unnecessary copying.
• Overloaded Function Call Operator (operator()(uint row, uint col)): After creating a (non-dynamically allocated) Matrix object, the user should be able to access the elements using the function call operator (as an alternative to using the at function):
Matrix a(1, 1);
a(0, 0) = 5;
cout << a(0,0) << endl;
(should print out 5).
Overloaded Non-Member Arithmetic Operators for Scalers: You should have already created overloads to support the basic arithmetic operations where the right-hand-side of an operation is a scaler value. Now you need to implement operator overloads so that scalers can be used on the left-hand-side of an operation. Here is an example showing the operators that you need to support:
Matrix a = {{1, 2}, {3, 4}};
Matrix b = 4.0 + a; // [ 5, 6 ]
// [ 7, 8 ]
Matrix c = 4.0 - a; // [ 3, 2 ]
// [ 1, 0 ]
Matrix d = 2.0 * a; // [ 2, 4 ]
// [ 6, 8 ]
Matrix e = 12.0 / a; // [ 12, 6 ] [ 4, 3 ]
Explanation / Answer
struct Matrix {
static int const row = 2, col = 2;
int A[ row][col];
};
istream &operator>>(istream &in, Matrix &m)
{
for (int i = 0; i < m.row; ++i) {
for (int j = 0; j < m.col; ++j)
if ( ! (in >> m.A[i][j]) ) return in;
}
return in;
}
ostream &operator<<(ostream &out, const Matrix &m)
{
for (int i = 0; i < m.row; ++i) {
for (int j = 0; j < m.col; ++j)
out << m.A[i][j] << " ";
out << endl;
}
return out;
}
int main() {
Matrix M;
cin >> M;
cout << M;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.