윤성우의 열헐 C++

윤성우의 열혈 c++) Chapter 03. 클래스의 기본

tose33 2022. 3. 14. 17:31

문제 03-1 [구조체 내에 함수정의하기]

#include <iostream>
using namespace std;

struct Point
{
    int xpos;
    int ypos;

    void MovePos(int x, int y);
    void AddPoint(const Point &pos);
    void ShowPosition();
};

void Point::MovePos(int x, int y)
{
    xpos += x;
    ypos += y;
}

void Point::AddPoint(const Point &pos)
{
    xpos += pos.xpos;
    ypos += pos.ypos;
}

void Point::ShowPosition()
{
    cout << "[" << xpos << ", " << ypos << "]" << endl;
}

int main()
{
    Point pos1 = {12, 4};
    Point pos2 = {20, 30};

    pos1.MovePos(-7, 10);
    pos1.ShowPosition();

    pos1.AddPoint(pos2);
    pos1.ShowPosition();
}

 

문제 03-2 [클래스의 정의] 

문제 1

 

Calculator.h 

//
// Created by lsh on 2022/03/14.
//

#ifndef CHAP03_2_1_CALCULATOR_H
#define CHAP03_2_1_CALCULATOR_H

class Calculator
{
private:
    int addCnt;
    int divCnt;
    int minCnt;
    int mulCnt;

public:
    void Init();
    double Add(double a, double b);
    double Div(double a, double b);
    double Min(double a, double b);
    double Mul(double a, double b);
    void ShowOpCount();

};

#endif //CHAP03_2_1_CALCULATOR_H

 

Calculator.cpp

#include "Calculator.h"
#include <iostream>
using namespace std;

void Calculator::Init()
{
    addCnt = 0;
    divCnt = 0;
    minCnt = 0;
    mulCnt = 0;
}

double Calculator::Add(double a, double b)
{
    addCnt++;
    return a + b;
}

double Calculator::Div(double a, double b)
{
    divCnt++;
    return a / b;
}

double Calculator::Min(double a, double b)
{
    minCnt++;
    return a - b;
}

double Calculator::Mul(double a, double b)
{
    mulCnt++;
    return a * b;
}

void Calculator::ShowOpCount()
{
    cout << "덧셈: " << addCnt << ' ';
    cout << "뺄셈: " << minCnt << ' ';
    cout << "곱셈: " << mulCnt << ' ';
    cout << "나눗셈: " << divCnt << endl;
}

 

문제 2

#include <iostream>
#include <string>
using namespace std;

class Printer
{
private:
    string str;

public:
    void SetString(string s);
    void ShowString();
};

void Printer::SetString(string s)
{
    str = s;
}

void Printer::ShowString()
{
    cout << str << endl;
}

int main()
{
    Printer pnt;
    pnt.SetString("HELLO WORLD");
    pnt.ShowString();
}