C++ 언어/연습문제
C++언어 연습문제31
powerdeng
2022. 11. 11. 14:07
[문제]
아래의 실행결과와 main함수를 참고하여 Person class와 UnivStudent class를 정의하라.
조건) UnivStudent 는 유도 클래스로, Person은 기초 클래스로 정의하라.
int main(void)
{
UnivStudent ust1("Lee", 22, "Computer eng.");
ust1.WhoAreYou();
UnivStudent ust2("Yoon", 21, "Electronic eng.");
ust2.WhoAreYou();
return 0;
}
[실행결과]
My name is Lee
I'm 22 years old
My major is Computer eng.
My name is Yoon
I'm 21 years old
My major is Electronic eng.
[코드]
#include<iostream>
using namespace std;
class Person
{
private:
int age;
char name[50];
public:
Person(int myage, const char* myname) :age(myage)
{
strcpy(name, myname);
}
void WhatYourName() const
{
cout << "My name is " << name << endl;
}
void HowOldAreYou() const
{
cout << "I'm " << age << " years old" << endl;
}
};
class UnivStudent : public Person
{
private:
char major[50];
public:
UnivStudent(const char* myname, int myage, const char* mymajor)
:Person(myage, myname)
{
strcpy(major, mymajor);
}
void WhoAreYou() const
{
WhatYourName();
HowOldAreYou();
cout << "My major is " << major << endl << endl;
}
};
int main(void)
{
UnivStudent ust1("Lee", 22, "Computer eng.");
ust1.WhoAreYou();
UnivStudent ust2("Yoon", 21, "Electronic eng.");
ust2.WhoAreYou();
return 0;
}
<참고>
윤성우의 열혈 C++ 프로그래밍