본문 바로가기

프로그래머/C, C++

[HackerRank] Virtual Functions | 클래스 상속 | 가상함수 | 클래스 정적 멤버변수

Virtual Functions

이 문제의 핵심은 3가지이다.

  1. 클래스 상속의 사용
  • Professor class와 Student class는 Person class를 상속 받는다.
  1. 가상함수의 사용
  • Person class는 getdata와 putdata 2개의 가상함수를 사용한다.
  1. 클래스 정적 멤버변수의 사용
  • 각 클래스의 정적 멤버변수가 존재해, 클래스 갯수를 count한다.
  • 클래스 정적 멤버변수는 해당 클래스 내에서 공유된다.

모범답안

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

class Person{
public:
    string name;
    int age;

    virtual void putdata(){}
    virtual void getdata(){}
};

class Professor : public Person{
public:
    int publications;
    static int id;
    int cur_id;
    Professor(){
        this->cur_id = ++id;
    }
    void getdata(){
        cin >> this->name >> this->age >> this->publications;
    } 
    void putdata(){
        cout << this->name << " "
            << this->age << " "
            << this->publications << " "
            << this->cur_id << endl;
    }
};
int Professor::id = 0;

class Student : public Person{
public:
    int marks[6];
    int cur_id;
    static int id;
    Student(){
        this->cur_id = ++id;        
    }
    void getdata(){
        cin >> this->name >> this->age;
        for(int i=0; i<6; i++){
            cin >> marks[i];
        }
    }
    void putdata(){
        int marksSum = 0;
        for(int i=0; i<6; i++){
            marksSum += marks[i];
        }
        cout << this->name << " "
            << this->age << " "
            << marksSum << " "
            << this->cur_id << endl;
    }
};
int Student::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;

}

핵심 문법

  1. 클래스 상속

    class Professor : public Person{
     //...
    }
  2. 가상함수

    class Person{
    public:
     // ...
     virtual void putdata(){}
     virtual void getdata(){}
    };
  3. 클래스 정적 멤버변수

    class Professor : public Person{
    public:
     // ...
     static int id;
     int cur_id;
     Student(){
         this->cur_id = ++id;        
     }
     //...
    }
    int Professor::id = 0;    // 다음과 같이 초기화