C++

예제1

khon98 2021. 1. 21. 09:59
#include <iostream>

using namespace std;

const int ROW = 3;
const int COL = 3;

class Matrix {
    int m_row, m_col; // 행과 열
    double *m_data; // 행렬 데이터
public:
    Matrix(int r = ROW, int c = COL);
    
    Matrix(const Matrix &other);
    
    Matrix& operator = (const Matrix &other);
    
    ~Matrix() { delete [] m_data; };
    
    Matrix operator + (const Matrix &other) const;
    
    friend ostream& operator << (ostream& os, const Matrix& M);
        
    double& operator () (int i, int j) { return m_data[i * m_col + j]; }
    
    double operator () (int i, int j) const {return m_data[i * m_col + j]; }
};

// 생성자
Matrix::Matrix(int r, int c) {
    m_row = r;
    m_col = c;
    m_data = new double[r * c];
}

// 복사 생성자
Matrix::Matrix(const Matrix &other) {
    m_row = other.m_row;
    m_col = other.m_col;
    m_data = new double[m_row * m_col];
    for (int i = 0; i < m_row; i++)
    for (int j = 0; j < m_col; j++)
    m_data[i * m_col + j] = other.m_data[i * m_col + j];
}

// 대입 연산자
Matrix&
Matrix::operator = (const Matrix &other) {
    if ( this == &other ) return *this;
    delete [] m_data;
    m_row = other.m_row;
    m_col = other.m_col;
    m_data = new double[m_row * m_col];
    for (int i = 0; i < m_row; i++)
    for (int j = 0; j < m_col; j++)
    m_data[i * m_col + j] = other.m_data[i * m_col + j];
    return *this;
}

// 행렬의 덧셈
Matrix
Matrix::operator + (const Matrix& other) const {
    Matrix result;
    
    for (int i = 0; i < m_row; i++)
    for (int j = 0; j < m_col; j++)
    result(i, j) = m_data[i * m_col + j] + other.m_data[i * m_col + j];
    
    return result;
}

// 출력 연산자
ostream& operator << (ostream& os, const Matrix& M) {
    for (int i = 0; i < M.m_row; i++) {
        for (int j = 0; j < M.m_col; j++)
        os << M(i, j) << '\t';
        os << endl;
    }
    return os;
}

int main(int argc, const char * argv[]) {
    Matrix D, B, C;
    for (int i = 0; i < ROW; i++)
    for (int j = 0; j < COL; j++)
    B(i, j) = D(i, j) = i + j;
    C = D + B;
    cout << C;
    return 0;
}

 

실행 결과

0 2 4

2 4 6 

4 6 8 

 

 

8 ~ 27 - 클래스를 선언, 클래스를 통해 사용자 타입 Matrix를 만듦

9 ~ 10 - 행렬의 자료구조를 나타냄

12 ~ 26 - 행렬에 대한 연산을 나타냄, 클래스는 객체의 자료구조와 그 객체에 대한 연산을 함께 묶어 제공

30 ~ 80 - 클래스 선언 이후, 즉 클래스에서 제공하는 연산에 대한 정의

82 ~ 90 - main() 함수 부분이 서비스를 사용하는 클라이언트 코드이고, 그 이전 코드는 모두 서비스를 제공하기 위한 서버 코드