Docsity

Assignment Operator and Matrix Operators in C++: Lecture 45, Exercises of Computer Programming

Partial preview of the text

Download Assignment Operator and Matrix Operators in C++: Lecture 45 and more Exercises Computer Programming in PDF only on Docsity!

Introduction to Programming

Lecture 45

Assignment Operator A = B

Assignment Operator ( A = B ) = C

Self Assignment

A = A

Class Matrix numRows = m.numRows ; numCols = m.numCols ; for ( int i = 0 ; i < numRows ; i ++ ) { for ( int j = 0 ; j < numCols ; j ++ ) { elements [ i ] [ j ] = m.elements [ i ] [ j ] ; } } } return * this ; }

Addition Operator

Class Matix Matrix Matrix :: operator + ( Matrix & m ) const { // Check for conformability if ( numRows == m.numRows && numCols == m.numCols ) { Matrix temp ( * this ) ; for ( int i = 0 ; i < numRows ; i ++ ) { for ( int j = 0 ; j < numCols ; j ++) { temp.elements [ i ] [ j ] += m.elements [ i ] [ j ] ; } } return temp ; } Matrix temp ( * this ) ; return temp ; } 8: Docsity.com

+= Operator

Class Matrix const Matrix & Matrix :: operator += ( Matrix & m ) {

  • this = * this + m ; return * this ; }

Class Matrix Matrix Matrix :: operator + ( double d ) const { Matrix temp ( * this ) ; for ( int i = 0 ; i < numRows ; i ++ ) { for ( int j = 0 ; j < numCols ; j ++ ) { temp.elements [ i ] [ j ] += d ; } } return temp ; } Docsity.com


Operator**

Class Matrix Matrix Matrix :: operator * ( const Matrix & m ) { Matrix temp ( numRows , m.numCols ) ; if ( numCols == m.numRows ) { for ( int i = 0 ; i < numRows ; i ++ ) { for ( int j = 0 ; j < m.numCols ; j ++ ) { temp.elements [ i ] [ j ] = 0.0 ; for ( int k = 0 ; k < numCols ; k ++ ) { temp.elements [ i ] [ j ] += elements [ i ] [ k ] * m.elements [ k ] [ j ] ; } } } } return temp ; }

Matrix / d Check d = 0?

Extraction Operator << Insertion Operator