본문 바로가기

언어/C++

7장 5~6번 Matrix 연산하기

#include <iostream>
using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class Matrix{
	int mat[2][2];
	public :
	Matrix(int a=0,int b=0, int c=0,int d=0){
		mat[0][0]=a;
		mat[0][1]=b;
		mat[1][0]=c;
		mat[1][1]=d;
	}	
	
	Matrix operator+(Matrix b){
		Matrix temp;
		for(int i=0; i<2; i++){
			for(int j=0; j<2; j++){
				temp.mat[i][j]= mat[i][j]+b.mat[i][j];
			}
		}
		return temp;
	}
	
	Matrix operator+=(Matrix b){
		for(int i=0; i<2; i++){
			for(int j=0; j<2; j++){
				mat[i][j]+=b.mat[i][j];
			}
		}	
		return *this;
	}	

	bool operator == (Matrix b){
		int count=0;
		for(int i=0; i<2; i++){
			for(int j=0; j<2; j++){
				if(mat[i][j] == b.mat[i][j]) count++;
			}
		}
		if(count==4) return true;
		else return false;
	}
	
	void show(){
		
		cout <<"Matrix={";
		for(int i=0; i<2;i++){
			for(int j=0; j<2; j++){
				cout<<mat[i][j]<< " ";
			}
		}
		cout << "}" << endl;
	}
};

int main(int argc, char** argv) {
	
	Matrix a(1,2,3,4);
	Matrix b(2,3,4,5);
	Matrix c;
	c=a+b;
	a+=b;
	a.show();
	b.show();
	c.show();
	
	if(a==c)
		cout<<"c and a are the same" << endl;

	return 0;
}
#include <iostream>
using namespace std;


/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class Matrix{
	
	int mat[4];
	
	public:
		Matrix (int a=0, int b=0, int c=0, int d=0){
			mat[0]=a;
			mat[1]=b;
			mat[2]=c;
			mat[3]=d;
		}
	
		void operator >> (int n[]){
			for(int i=0; i<4; i++){
				n[i]=mat[i];
			}
		}
		
		void operator << (int n[]){
			for(int i=0; i<4; i++){
				mat[i]=n[i];
			}
		}
			
		void show(){
			cout <<"Matrix ={";
			for(int i=0; i<4; i++){
				cout<<mat[i]<<' ';
			}
			cout << "}" << endl;
		}

};

int main(int argc, char** argv) {
	
	Matrix a(4,3,2,1);
	Matrix b;
	int x[4];
	int y[4]={1,2,3,4};
	a>>x;
	b<<y;
	
	for(int i=0; i<4; i++){
		cout <<x[i]<< ' ';
	}
	cout << endl;
	b.show();
	
	return 0;
}