본문 바로가기

프로그래밍 언어/C, C++

[Hackerrank] 14. Classes

14. 클래스

[ 난이도: Easy | 분야: Classes ]

1. 내용 정리

C++에서 클래스는 사용자 정의 타입으로 데이터와 함수들을 가지고 class라는 단어로 정의되는 것이다.

비록 클래스와 구조체가 기능적인 측면에서 동일한 자료형을 가지지만, 근본적인 차이가 있다.

클래스의 데이터 맴버들은 기본적으로 private이고 구조체의 데이터 맴버들은 기본적으로 public이다.

common block에서 다중 데이터를 저장할 때, 데이터를 조작/접근하기 위해서는 특정한 함수(method라고 알려져 있다)가 필요하다.

이것은 객체지향 프로그래밍의 기반 블록(building block)처럼 제공된다.

구조체는 멤버 요소들의 접근을 제한하는 접근 구분자(access specifier) 또한 있다.

기본적으로 사용하는 것들은 다음과 같다:

- public: 공용 멤버들(변수, 메소드)은 코드의 어느 곳에서나 접근할 수 있다.

- private: private 맴버들은 오직 다른 멤버 함수에서만 접근할 수 있고 클래스의 밖에서는 접근할 수 없다.

클래스는 다음과 같은 구조를 갖는다:

class ClassName {
    access_specifier1:
        type1 val1;
        type2 val2;
        ret_type1 method1(type_arg1 arg1, type_arg2 arg2,...)
        ...
    access_specifier2:
        type3 val3;
        type4 val4;
        ret_type2 method2(type_arg3 arg3, type_arg4 arg4,...)
        ...
};

이것은 모든 변수들을 private으로 설정하고 public 메소드에서는 set/get으로 접근하는 기본적인 예제다.

예를 들어:

class SampleClass {
    private:
        int val;
    public:
        void set(int a) {
            val = a;
        }
        int get() {
            return val;
        }
};

우리는 나이(정수), 이름(문자열), 성씨(문자열) 그리고 standard(정수)로 이루어진 학생 클래스에 세부사항들을 넣을 수 있다.

 

2. 과제

우리는 나이(정수), 이름(문자열), 성씨(문자열) 그리고 standard(정수)로 이루어진 class를 가지고 있다.

각 요소별 setter와 getter를 만들어라:

이 말은 클래스가 적어도 아래의 기능을 수행할 수 있어야 한다는 뜻이다.

- get_age, set_age

- get_first_name, set_first_name

- get_last_name, set_last_name

- get_standard, set_standard

또한 to_string()이라는 위의 쉼표로 구분된 두 요소들로 구성된 문자열을 반환할 때 사용하는 메소드를 만들어라.

이것을 위해 stringstream을 사용해도 좋다.

입력 형식

입력은 총 네 줄로 이루어져 있다.

첫 번째 줄은 정수이고 나이를 나타낸다.

두 번째 줄은 소문자로 이루어진 문자열이고 학생의 이름을 나타낸다.

세 번째 줄은 소문자로 이루어진 또 다른 문자열이고 학생의 성씨를 나타낸다.

네 번째 줄은 정수로 학생의 standard를 나타낸다.

주의: 이름과 성씨는 50자를 넘지 않는다.

출력 형식

HackerRank에서 제공된 코드는 Student class에서 클래스 멤버들을 설정하거나 가져오는데 사용된다.

입력 예시

15
john
carmack
10

출력 예시

15
carmack, john
10

15, john, carmack, 10

문제

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

/*
Enter code for class Student here.
Read statement for specification.
*/

int main() {
    int age, standard;
    string first_name, last_name;
    
    cin >> age >> first_name >> last_name >> standard;
    
    Student st;
    st.set_age(age);
    st.set_standard(standard);
    st.set_first_name(first_name);
    st.set_last_name(last_name);
    
    cout << st.get_age() << "\n";
    cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
    cout << st.get_standard() << "\n";
    cout << "\n";
    cout << st.to_string();
    
    return 0;
}#include <iostream>
#include <sstream>
using namespace std;

/*
Enter code for class Student here.
Read statement for specification.
*/

int main() {
    int age, standard;
    string first_name, last_name;
    
    cin >> age >> first_name >> last_name >> standard;
    
    Student st;
    st.set_age(age);
    st.set_standard(standard);
    st.set_first_name(first_name);
    st.set_last_name(last_name);
    
    cout << st.get_age() << "\n";
    cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
    cout << st.get_standard() << "\n";
    cout << "\n";
    cout << st.to_string();
    
    return 0;
}
더보기

정답

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

/*
Enter code for class Student here.
Read statement for specification.
*/
class Student {
    private:
        int age;
        string first_name;
        string last_name;
        int standard;
    public:
        void set_age(int age) {
            this->age = age;
        }
        void set_standard(int standard) {
            this->standard = standard;
        }
        void set_first_name(string first_name) {
            this->first_name = first_name;
        }
        void set_last_name(string last_name) {
            this->last_name = last_name;
        }
        int get_age() {
            return age;
        }
        int get_standard() {
            return standard;
        }
        string get_first_name() {
            return first_name;
        }
        string get_last_name() {
            return last_name;
        }
        string to_string() {
            ostringstream ss;
            ss << age << "," << first_name << "," << last_name << "," << standard;
            return ss.str();
        }
};

int main() {
    int age, standard;
    string first_name, last_name;
    
    cin >> age >> first_name >> last_name >> standard;
    
    Student st;
    st.set_age(age);
    st.set_standard(standard);
    st.set_first_name(first_name);
    st.set_last_name(last_name);
    
    cout << st.get_age() << "\n";
    cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
    cout << st.get_standard() << "\n";
    cout << "\n";
    cout << st.to_string();
    
    return 0;
}

 

 

 

 

©️ Hackerrank. All Rights Reserved.

'프로그래밍 언어 > C, C++' 카테고리의 다른 글

[Hackerrank] 16. Box It!  (0) 2024.02.13
[Hackerrank] 15. Classes and Objects  (2) 2024.02.09
[Hackerrank] 13. Structs  (0) 2024.02.09
[Hackerrank] 11. Strings  (0) 2024.02.08
[Hackerrank] 10. StringStream  (0) 2024.02.08