7.6> 2차원 행렬을 추상화한 Matrix 클래스를 활용하는 다음 코드가 있다.
(1) <<. >> 연산자 함수를 Matrix의 멤버 함수로 구현하라.
<코드1>
#include <iostream>
using namespace std;
class Matrix{ private: int mat[4]; //인트형 배열 크기는 4 public: Matrix(int x0=0,int x1=0,int x2=0,int x3=0); //각 디폴트 매개변수는 0 void show(); void operator>>(int *x); void operator<<(int *y); }; Matrix::Matrix(int x0,int x1, int x2, int x3){ mat[0]=x0; mat[1]=x1; //멤버 인트 배열을 매개변수로 차례로 초기화 mat[2]=x2; mat[3]=x3; } void Matrix::show(){ //출력함수 cout<<"Matrix = {"; for(int i=0;i<4;i++) {cout<<" "<<mat[i];} cout<<" }"<<endl; }
void Matrix::operator>>(int *x){ //x가 가리키는 배열에 객체 내 배열 원소 차례로 대입 for(int i=0;i<4;i++){ x[i]=(this->mat)[i]; } } void Matrix::operator<<(int *y){ //객체 내 배열에 y가 가리키는 배열 원소 차례로 대입 for(int i=0;i<4;i++){ (this->mat)[i]=y[i]; } } int main(void){
Matrix a(4,3,2,1), b; int x[4], y[4]={1,2,3,4}; //2차원 행렬의 4개 원소 값 a>>x; //a의 각 원소를 배열 x에 복사, x[]는 {4,3,2,1} b<<y; // 배열 y의 원소 값을 b의 각 원소에 설정 for(int i=0;i<4;i++) cout<<x[i]<<" "; //x[]출력 cout<<endl; b.show(); return 0; } |
(2) <<. >> 연산자 함수를 Matrix의 프렌드 함수로 구현하라.
<코드2>
#include <iostream>
using namespace std;
class Matrix{ private: int mat[4]; //인트형 배열 크기는 4 public: Matrix(int x0=0,int x1=0,int x2=0,int x3=0); //각 디폴트 매개변수는 0 void show(); friend void operator>>(Matrix op1,int *op2); friend void operator<<(Matrix &op1,int *op2); }; Matrix::Matrix(int x0,int x1, int x2, int x3){ mat[0]=x0; mat[1]=x1; //멤버 인트 배열을 매개변수로 차례로 초기화 mat[2]=x2; mat[3]=x3; } void Matrix::show(){ //출력함수 cout<<"Matrix = {"; for(int i=0;i<4;i++) {cout<<" "<<mat[i];} cout<<" }"<<endl; } void operator>>(Matrix op1,int *op2){ //객체의 값을 배열에 대입 for(int i=0;i<4;i++){ op2[i]=(op1.mat)[i]; } } void operator<<(Matrix &op1,int *op2){ //배열의 값을 객체에 대입 for(int i=0;i<4;i++){ (op1.mat)[i]=op2[i]; } }
int main(void){
Matrix a(4,3,2,1), b; int x[4], y[4]={1,2,3,4}; //2차원 행렬의 4개 원소 값 a>>x; //a의 각 원소를 배열 x에 복사, x[]는 {4,3,2,1} b<<y; // 배열 y의 원소 값을 b의 각 원소에 설정 for(int i=0;i<4;i++) cout<<x[i]<<" "; //x[]출력 cout<<endl; b.show(); return 0; } |
<결과창>
|
'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글
Circle class 오퍼레이터 오버로딩 (0) | 2017.12.25 |
---|---|
Circle class (0) | 2017.12.25 |
Matrix class (0) | 2017.12.25 |
Trace 클래스 (0) | 2017.12.25 |
Random 클래스 (0) | 2017.12.25 |