C++

[C++] 명품 C++ 프로그래밍 실습문제 7장 6번

Hs’s Coding vlog 2023. 1. 11. 21:44

[C++]명품 C++ 프로그래밍 실습문제 7장 6번

[C++]명품 C++ programming 실습문제 7장 6번

명품 C++ 프로그래밍실습문제/연습문제 /C++

//6-1
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;
class Matrix{
    int matrix[100];
public:
    Matrix(int a=0,int b=0,int c=0,int d=0){
        matrix[0] = a;
        matrix[1] = b;
        matrix[2] = c;
        matrix[3] = d;
    }
    Matrix operator+(Matrix &r) //멤버함수로 설정해서 보기
    {
        Matrix tmp;
        for(int i=0;i<4;i++){
            tmp.matrix[i] = r.matrix[i]+this->matrix[i];
        }
        
        
        return tmp;
        
    }
    Matrix operator +=(Matrix &r)
    {
        for(int i=0 ; i<4; i++){
            this->matrix[i] = this->matrix[i] + r.matrix[i];
        }
        return *this;
    }
    
    bool operator ==(Matrix &r){
        if(this->matrix[0] == r.matrix[0] && this->matrix[1] == r.matrix[1] &&
           this->matrix[2] == r.matrix[2] && this->matrix[3] == r.matrix[3] )
            return true;
        else return  false;
    }
    
    void show(){
        cout << "Matrix = {" ;
        for(int i=0 ; i<4; i++){
            cout << this->matrix[i] << " " ;
        }
        cout << "}" << endl;
    }
};

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


//6-2
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;
class Matrix{
    int matrix[100];
public:
    Matrix(int a=0,int b=0,int c=0,int d=0){
        matrix[0] = a;
        matrix[1] = b;
        matrix[2] = c;
        matrix[3] = d;
    }
    friend Matrix operator+(Matrix &l ,Matrix &r); //멤버함수로 설정해서 보기
    friend Matrix operator +=(Matrix &l ,Matrix &r);
    friend bool operator ==(Matrix &l ,Matrix &r);
  
    void show(){
        cout << "Matrix = {" ;
        for(int i=0 ; i<4; i++){
            cout << this->matrix[i] << " " ;
        }
        cout << "}" << endl;
    }
};
Matrix operator+(Matrix &l ,Matrix &r) //멤버함수로 설정해서 보기
{
    Matrix tmp;
    for(int i=0;i<4;i++){
        tmp.matrix[i] = r.matrix[i]+l.matrix[i];
    }
    
    
    return tmp;
    
}
Matrix operator +=(Matrix &l ,Matrix &r)
{
    for(int i=0 ; i<4; i++){
        l.matrix[i] = l.matrix[i] + r.matrix[i];
    }
    return l;
}

bool operator ==(Matrix &l ,Matrix &r){
    if(l.matrix[0] == r.matrix[0] && l.matrix[1] == r.matrix[1] &&
       l.matrix[2] == r.matrix[2] && l.matrix[3] == r.matrix[3] )
        return true;
    else return  false;
}

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