[Hackerrank] C++ - 19 Virtual Functions

후유카와·2024년 11월 22일

Hackerrank

목록 보기
18/59

19. Virtual Functions

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

1. 과제

이번 문제는 가상 함수에 익숙해지기 위해 준비했다.

Person, Professor 그리고 Student, 세 개의 클래스를 생성하라.

Person 클래스는 데이터 멤버로 name과 age를 갖는다.

Professor 클래스와 Student 클래스는  Person 클래스로부터 상속을 받는다.

Professor 클래스는 두 개의 정수 멤버를 갖는다: publications, cur_id

또한 두 개의 함수 멤버를 갖는다: getdata, putdata

함수 getdata는 사용자로부터 입력을 받는다: name, age 그리고 교수의 publications

함수 putdata는 name, age, professor의 publications와 cur_id를 출력한다.

Student 클래스는 두 개의 데이터 멤버를 갖는다: 크기가 6인 배열인 marks, cur_id

이 클래스는 두 개의 함수를 갖는다: getdata, putdata

함수 getdata는 사용자로부터 입력을 받는다: name, age, 그리고 6 과목의 student의 marks

함수 putdata는 name, age, 학생의 marks의 합 그리고 cur_id를 출력한다.

Professor 클래스나 Student 클래스의 객체를 생성할 때 sequential id는 1부터 순차적으로 할당된다.

이 문제를 가상 함수, 생성자 그리고 static variables를 이용하여 풀어라.

만약 더 많은 데이터 멤버가 필요하다면 추가해도 상관 없다.

노트: 입력이 어떻게 다루어지는 확인하기 위해 메인 함수를 열어봐라.

입력 형식

입력의 첫 번째 줄은 생성할 객체의 개수를 담고 있다.

만약 각 객체의 입력의 첫 번째 줄이 1이라면, 이것은 Professor 클래스의 객체를 만드는 것이다.

이 경우 name, age 그리고 교수의 publications를 입력 받아야 한다.

만약 각 객체의 입력의 두 번째 줄이 2라면, 이것은 Studenet 클래스의 객체를 만드는 것이다.

이 경우, name, age 그리고 학생의 6 과목 점수를 입력 받아야 한다.

제약 사항

이름의 길이는 1보다 크거나 같고 100보다 작거나 같다.

age는 1보다 크거나 같고 80보다 작거나 같다.

publications는 1보다 크거나 같고 1000보다 작거나 같다.

학생의 각 교과목 점수는 0보다 크거나 같고 100보다 작거나 같다.

출력 형식

객체의 의존적인 두 가지의 형식이 있다.

만약 객체의 형식이 Professor라면, 공백으로 구분된 name, age, publications 그리고 id를 새로운 줄에 출력해라.

만약 객체의 형식이 Student라면, 공백으로 구본된 name, age, 6과목 점수의 합 그리고 id를 새로운 줄에 출력해라.

입력 예시

4
1
Walter 56 99
2
Jesse 18 50 48 97 76 34 98
2
Pinkman 22 10 12 0 18 45 50
1
White 58 87

출력 예시

Walter 56 99 1
Jesse 18 403 1
Pinkman 22 135 2
White 58 87 2

문제

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main(){

    int n, val;
    cin>>n; //The number of objects that is going to be created.
    Person *per[n];

    for(int i = 0;i < n;i++){

        cin>>val;
        if(val == 1){
            // If val is 1 current object is of type Professor
            per[i] = new Professor;

        }
        else per[i] = new Student; // Else the current object is of type Student

        per[i]->getdata(); // Get the data from the user.

    }

    for(int i=0;i<n;i++)
        per[i]->putdata(); // Print the required output for each object.

    return 0;

}

더보기

정답

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

// My Code
class Person{
    public:
        string name; // name
        int age; // age
        virtual void getdata() {};
        virtual void putdata() {};
};

class Professor : public Person {
    // DATA
    private:
        int publications;
        int cur_id;
    // MEMBER
    public:
        static int s_cur_id;
        virtual void getdata() {
            cin >> name >> age >> publications;
            s_cur_id++;
            cur_id = s_cur_id;
        }
        virtual void putdata() {
            cout << name << " " << age << " " << publications << " " << cur_id << endl;
        }
        
};

class Student : public Person {
    // DATA
    private:
        vector <int> marks;
        int cur_id;
    public:
        static int s_cur_id;
        virtual void getdata() {
            cin >> name >> age;
            for(int i = 0; i < 6; i++) {
                int mark = 0;
                cin >> mark;
                marks.push_back(mark);           
            }
            s_cur_id++;
            cur_id = s_cur_id;
        }
        virtual int myMarkSum() {
            int result = 0;
            for(int i = 0; i < 6; i++) {
                result += marks[i];
            }
            return result;
        }
        void putdata() {
            cout << name << " " << age << " " << myMarkSum() << " " << cur_id << endl;
        }
};

int Professor::s_cur_id = 0;
int Student::s_cur_id = 0;

int main(){

    int n, val;
    cin>>n; //The number of objects that is going to be created.
    Person *per[n];

    for(int i = 0;i < n;i++){

        cin>>val;
        if(val == 1){
            // If val is 1 current object is of type Professor
            per[i] = new Professor;

        }
        else per[i] = new Student; // Else the current object is of type Student

        per[i]->getdata(); // Get the data from the user.

    }

    for(int i=0;i<n;i++)
        per[i]->putdata(); // Print the required output for each object.

    return 0;

}

©️Hackerrank. All Rights Reserved.

profile
안녕하세요! 저는 전자공학을 전공하며 하드웨어와 소프트웨어 모두를 깊이 있게 공부하고 있는 후유카와입니다. Verilog HDL, C/C++, Java, Python 등 다양한 프로그래밍 언어를 다루고 있으며, 최근에는 알고리즘에 대한 학습에 집중하고 있습니다. 기술적인 내용을 공유하고, 함께 성장할 수 있는 공간이 되기를 바랍니다. 잘못된 내용이나 피드백은 언제나 환영합니다! 함께 소통하며 더 나은 지식을 쌓아가요. 감사합니다!

0개의 댓글