[디딤돌 C++] 23. 캡슐화 최종 실습 – 멤버 필드

먼저 클래스 이름은 Student로 정할게요.

주민 번호는 변하지 않으므로 상수화 멤버 필드로 정의하세요.

const int pn;//주민번호

주민 번호를 순차적으로 부여하기 위해 정적 멤버 필드로 가장 최근에 부여한 주민 번호가 필요하겠죠.

static int last_pn;//가장 최근에 부여한 주민 번호

이름은 문자열로 정하면 되겠죠.

string name;//이름

지력과 체력, 스트레스, 연속으로 공부한 횟수는 정수 형식으로 정의하면 되겠네요.

int iq;//지력
int hp;//체력
int stress;//스트레스
int scnt;//연속으로 공부한 횟수

최소값, 최대값, 디폴트 값은 형식 내에 정해진 값이므로 정적 상수화 멤버 필드로 선언하세요.

//능력치의 디폴트, 최소, 최대값
static const int def_iq;
static const int min_iq;
static const int max_iq;

static const int def_hp;
static const int min_hp;
static const int max_hp;

static const int def_stress;
static const int min_stress;
static const int max_stress;

static const int def_scnt;
static const int min_scnt;
static const int max_scnt;

물론 정적 멤버 필드들은 클래스 외부에도 선언해 주어야 합니다. 특히 정적 상수화 멤버 필드는 상수 값을 설정해 주어야죠.

int Student::last_pn;
const int Student::def_iq=100;
const int Student::min_iq=0;
const int Student::max_iq=200;
const int Student::def_hp=100;
const int Student::min_hp=0;
const int Student::max_hp=200;
const int Student::def_stress=0;
const int Student::min_stress=0;
const int Student::max_stress=100;
const int Student::def_scnt=0;
const int Student::min_scnt=0;
const int Student::max_scnt=5;

현재까지 작성한 프로그램의 코드 내용입니다.

//Student.h
#pragma once
#include <string>
using namespace std;

class Student
{
    const int pn;//주민번호
    static int last_pn;//가장 최근에 부여한 주민 번호
    string name;//이름
    int iq;//지력
    int hp;//체력
    int stress;//스트레스
    int scnt;//연속으로 공부한 횟수

    //능력치의 디폴트, 최소, 최대값
    static const int def_iq;
    static const int min_iq;
    static const int max_iq;

    static const int def_hp;
    static const int min_hp;
    static const int max_hp;

    static const int def_stress;
    static const int min_stress;
    static const int max_stress;
    static const int def_scnt;
    static const int min_scnt;
    static const int max_scnt;
};
//Student.cpp
#include "Student.h"

int Student::last_pn;
const int Student::def_iq=100;
const int Student::min_iq=0;
const int Student::max_iq=200;
const int Student::def_hp=100;
const int Student::min_hp=0;
const int Student::max_hp=200;
const int Student::def_stress=0;
const int Student::min_stress=0;
const int Student::max_stress=100;
const int Student::def_scnt=0;
const int Student::min_scnt=0;
const int Student::max_scnt=5;
//Program.cpp
#include "Student.h"

int main()
{
    return 0;
}

이제 여러분은 캡슐화할 멤버 멤서드 이름과 입력 매개 변수 목록 및 반환 형식을 결정하세요.